我试图将我的JavaScript正则表达式经验转移到Python上,但是遇到了很大的问题。
我只是想让这个代码工作:
print(re.match('e','test'))
...但它打印出了None。如果我这样做:
print(re.match('e','est'))
它匹配...默认会匹配字符串的开头吗?当它匹配时,我如何使用结果?
我如何使第一个匹配项匹配?有比Python网站提供的更好的文档吗?
我试图将我的JavaScript正则表达式经验转移到Python上,但是遇到了很大的问题。
我只是想让这个代码工作:
print(re.match('e','test'))
...但它打印出了None。如果我这样做:
print(re.match('e','est'))
它匹配...默认会匹配字符串的开头吗?当它匹配时,我如何使用结果?
我如何使第一个匹配项匹配?有比Python网站提供的更好的文档吗?
re.match
隐式地在正则表达式的开头添加了 ^
。换句话说,它只匹配字符串的开头。
re.search
将在所有位置上尝试匹配。
一般而言,我建议使用 re.search
并在需要时显式地添加 ^
。
文档很清晰,我认为。
re.match(pattern, string[, flags])¶
If zero or more characters **at the beginning of string** match the
regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.