Python正则表达式不匹配

时间:2013-01-21 02:48:22

标签: python regex string

import re
str2='hello: acb cross'
reg = re.compile('hello: (a*) cross')
m = reg.search(str2)
print m
if m:
   nat= m.group(0)
   print(nat)

在上面的片段中,我希望输出为'hello:acb cross',如果我做组(1)它应该是'acb'。但我没有得到任何。 print m返回None。谁能告诉我它不起作用的原因。

但是如果我尝试这样的话,那就有效:

import re
str1 = "carter notes: dependent on stems"
r = re.compile('carter notes:(.*)stems')
m = r.search(str1)
if m:
   lx = m.group(1)
   #print(m.group(0))
   print(lx)

2 个答案:

答案 0 :(得分:2)

a*表示“任意数量的a s”。

.*表示“任意数量(任何单个字符)”。

你的意思是“a,后跟任意数量的(任何单个字符)”;那是a.*

答案 1 :(得分:0)

试试这个:

str2='hello: acb cross'
reg = re.compile('hello: (a.*?) cross')