Python正则表达式字符串匹配?

mow*_*ker 32 python regex pattern-matching

我有一段时间试图将我的javascript正则表达式转换为Python.

我只是想让这个工作:

print(re.match('e','test'))
Run Code Online (Sandbox Code Playgroud)

...但它打印无.如果我做:

print(re.match('e','est'))
Run Code Online (Sandbox Code Playgroud)

它匹配...它默认匹配字符串的开头吗?匹配时,如何使用结果?

如何进行第一场比赛?是否有比python网站提供的更好的文档?

Osc*_*orz 57

re.match隐含地增加^了你的正则表达式的开头.换句话说,它只匹配字符串的开头.

re.search 将在所有位置重试.

一般来说,我建议您在需要时明确使用re.search和添加^.

http://docs.python.org/library/re.html


Ken*_*ent 9

我认为文档很清楚.

re.match(pattern,string [,flags])

If zero or more characters **at the beginning of string** match the
Run Code Online (Sandbox Code Playgroud)

正则表达式模式,返回相应的MatchObject实例.如果字符串与模式不匹配,则返回None; 请注意,这与零长度匹配不同.