简体   繁体   English

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

[英]Python regex string matching?

I'm having a hell of a time trying to transfer my experience with javascript regex to Python. 我在尝试将我的javascript正则表达式经验转移到Python时遇到了麻烦。

I'm just trying to get this to work: 我只是想让它工作:

print(re.match('e','test'))

...but it prints None. ...但是它打印无。 If I do: 如果我做:

print(re.match('e','est'))

It matches... does it by default match the beginning of the string? 它匹配...默认情况下是否匹配字符串的开头? When it does match, how do I use the result? 当匹配时,如何使用结果?

How do I make the first one match? 我如何进行第一场比赛? Is there better documentation than the python site offers? 是否有比python网站提供的文档更好的文档?

re.match implicitly adds ^ to the start of your regex. re.match^隐式添加到正则表达式的开头。 In other words, it only matches at the start of the string. 换句话说,它仅在字符串的开头匹配。

re.search will retry at all positions. re.search将在所有位置重试。

Generally speaking, I recommend using re.search and adding ^ explicitly when you want it. 一般来说,建议您使用re.search并在需要时显式添加^

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

the docs is clear i think. 我认为文档很清楚。

re.match(pattern, string[, flags])¶ re.match(pattern,string [,标志])¶

 If zero or more characters **at the beginning of string** match the 

regular expression pattern, return a corresponding MatchObject instance. 正则表达式模式,返回相应的MatchObject实例。 Return None if the string does not match the pattern; 如果字符串与模式不匹配,则返回None;否则返回false。 note that this is different from a zero-length match. 请注意,这与零长度匹配不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM