使用finder正则表达式

时间:2013-08-11 00:46:16

标签: python regex

我试图找出这个表达式:

p = re.compile ("[I need this]")
for m in p.finditer('foo, I need this, more foo'):
    print m.start(), m.group()

我需要理解为什么我在第22条得到“e” 并正确地重写。

2 个答案:

答案 0 :(得分:2)

[]表示一个字符类,也就是说,在你的情况下,[我需要这个]代表:匹配一个字符:I,n,e,d,t,h,i ,s,和(也许)一个空间。它相当于[Inedthis ]。如果您想匹配整个短语,请省略括号。如果你想匹配括号,也要逃避它们:\[I ... \]

答案 1 :(得分:2)

使用[],您正在搜索字符类[ Idehinst],即字符集' ', 'I', 'd', 'e', 'h', 'i', 'n', 's', 't'

使用(...)匹配括号内的正则表达式,并指示组的开始和结束。

如果您要搜索群组:(I need this)

>>> import re
>>> p = re.compile ("(I need this)")
>>> for m in p.finditer('foo, I need this, more foo'):
...     print m.start(), m.group()
... 
5 I need this

有关详细信息,请参阅7.2.1. Regular Expression Syntax中的the official documentation

相关问题