为什么关于芬德尔()给我不同的结果芬代尔()在Python中?

2024-09-29 19:18:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个正则表达式:

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相同的结果??在


Tags: ofthenorearefirstallowedcompile
3条回答

当您给re.findall()一个包含组(圆括号表达式)的正则表达式时,它将返回匹配的。在这里,你只有一个组,最后是| or]]。另一方面,在你使用的代码中芬代尔(),您没有要求任何特定的组,因此它提供了整个字符串。在

你可以得到关于芬德尔()来做你想做的事情,在整个正则表达式的周围加上括号,或者只在你要提取的部分的周围加上圆括号。假设您试图解析wiki链接,那么第4行就是“一堆字符”。例如

p = re.compile(r'''
\[\[            #the first [[
[^:]*?          #no :s are allowed
(.*?)           #a bunch of chars
(
\|              #either go until a |
|\]\]           #or the last ]]
)
                ''', re.VERBOSE)

p.findall('   [[Imae|Lol]]     [[sdfef]]')

退货:

^{pr2}$

我认为^{} documentation的关键是:

If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

您的正则表达式有一个组围绕管道或关闭]]这里:

(
\|              #either go until a |
|\]\]           #or the last ]]
)

finditer()似乎没有这样的子句。在

Findall返回匹配组的列表。regex中的parathese定义了findall认为您想要的组,但是您不想要组。(?:...)是一种非捕获性妄想。将正则表达式更改为:

'''
\[\[            #the first [[
[^:]*?          #no :s are allowed
.*?             #a bunch of chars
(?:             #non-capturing group
\|              #either go until a |
|\]\]           #or the last ]]
)
                '''

相关问题 更多 >

    热门问题