Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python findall、组和管道_Python_Regex_Pipe_Findall - Fatal编程技术网

python findall、组和管道

python findall、组和管道,python,regex,pipe,findall,Python,Regex,Pipe,Findall,然而,我的问题是,我想实现一个管道(替代),以便将相同的正则表达式应用于 x = "type='text'" re.findall("([A-Za-z])='(.*?)')", x) # this will work like a charm and produce # ['type', 'text'] 基本上,下面的正则表达式应该可以工作,但使用findall会导致一些奇怪的结果: x = 'type="text"'

然而,我的问题是,我想实现一个管道(替代),以便将相同的正则表达式应用于

x = "type='text'"
re.findall("([A-Za-z])='(.*?)')", x) # this will work like a charm and produce
                                     # ['type', 'text']
基本上,下面的正则表达式应该可以工作,但使用findall会导致一些奇怪的结果:

x = 'type="text"' # see the quotes
我不能用['”]代替管道,因为它可能会导致糟糕的结果:

([A-Za-z])=('(.*?)')|"(.*?)")

现在,我如何构建这样一个适用于单引号或双引号的正则表达式呢?顺便说一句,请不要推荐任何html或xml解析器,因为我对它们不感兴趣。

shlex
在这里会做得更好,但是如果你坚持
re
,请使用
([a-Za-z]+)=(?p['])(.+?)(?p=quote)
shlex
在这里会做得更好,但是如果你坚持
re
,使用
([a-Za-z]+)=(?p['“])(.+?)(.p=quote)
问题是,在
([a-Za-z]+)=('(.*?)(.*)(.*)
你有四个组,你只需要两个(这可能是你发现结果奇怪的地方)。如果你使用就可以了。请记住,您可以通过放置
(?:)
来排除分组,因此这将是等效的:
([A-Za-z]+)=('(?:.*))|“(?:*?)”

编辑:我刚刚意识到,此解决方案将包括您不需要的周围引号。不过,您可以轻松地将其删除。您也可以使用反向引用,但这样您将有一个额外的组,该组应在最后删除,例如:

value="hey there what's up?"

给出了
[('type','text'),('type','text')]
问题是,在
([A-Za-z]+)=('(.*?)|“(.*)”
中,您有四个组,只需要两个(这可能是您发现结果奇怪的地方)。如果您使用
([A-Za-z]+)=('.'.'.'.'.''.'.'.'.*?“*?”)
然后就可以了。记住,您可以通过放置
(?:)
来排除分组,因此这是等效的:
([A-Za-z]+)=('(?:*))|“(?:*)”

编辑:我刚刚意识到,此解决方案将包括您不需要的周围引号。不过,您可以轻松地将其删除。您也可以使用反向引用,但这样您将有一个额外的组,该组应在最后删除,例如:

value="hey there what's up?"

谢谢你的好的正则表达式。你能举个例子说明你是如何用shlex做到这一点的吗
shlex
更倾向于类似shell的字典字符串,
re
非常适合,特别是你给出的这个很好的表达式。感谢你的好正则表达式。你能举个例子说明如何使用shlex做到这一点吗?
>[i.split('=',1)对于shlex.split中的i(“foo='bar\'baz'x=1 alpha='omega'))
[['foo','bar'baz'],['x','1'],['alpha','omega'].
shlex
更倾向于类似于shell的字典字符串,
re
非常适合,特别是您给出的这个精细表达式。