我写了一个正则表达式:
p = re.compile(r'''
\[\[ #the first [[
[^:]*? #no :s are allowed
.*? #a bunch of chars
(
\| #either go until a |
|\]\] #or the last ]]
)
''', re.VERBOSE)
我想使用re.findall
来获取某个字符串的所有匹配部分。我写了一些测试代码,但结果很奇怪。在
这个代码
^{pr2}$给我这个输出:
(3, 10)
[[Imae|
(20, 29)
[[sdfef]]
很有道理,对吧?但当我这么做的时候:
h = p.findall(' [[Imae|Lol]] [[sdfef]]')
for elem in h:
print elem
输出如下:
|
]]
为什么findall()不能打印出与finditer相同的结果??在
当您给
re.findall()
一个包含组(圆括号表达式)的正则表达式时,它将返回匹配的组。在这里,你只有一个组,最后是| or]]。另一方面,在你使用的代码中芬代尔(),您没有要求任何特定的组,因此它提供了整个字符串。在你可以得到关于芬德尔()来做你想做的事情,在整个正则表达式的周围加上括号,或者只在你要提取的部分的周围加上圆括号。假设您试图解析wiki链接,那么第4行就是“一堆字符”。例如
退货:
^{pr2}$我认为^{} documentation 的关键是:
您的正则表达式有一个组围绕管道或关闭]]这里:
finditer()
似乎没有这样的子句。在Findall返回匹配组的列表。regex中的parathese定义了findall认为您想要的组,但是您不想要组。
(?:...)
是一种非捕获性妄想。将正则表达式更改为:相关问题 更多 >
编程相关推荐