简体   繁体   English

没有为此正则表达式返回匹配项

[英]no match returned for this regular expression

I am using raw string notation to express a fairly simple regular expression and I am not getting a match object. 我正在使用原始字符串表示法来表达一个相当简单的正则表达式,但没有得到匹配对象。 Shell transcript follows: Shell脚本如下:

[~/Documents/Programming/rlm]$ python
python
Python 2.7.5 (default, Aug 25 2013, 00:04:04) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> s = 'bob2323'
s = 'bob2323'
>>> import re
import re
>>> re.match(r'\d+', s)
re.match(r'\d+', s)
>>> 

Use re.search instead of re.match , because re.match only matches from the start of the string.: 使用re.search而不是re.match ,因为re.match只匹配字符串的开头。

>>> re.search(r'\d+', s)
<_sre.SRE_Match object at 0xb5eefbf0>

re.match vs re.search : re.match VS re.search

re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string. re.match()仅在字符串的开头检查匹配项,而re.search()在字符串的任何位置检查匹配项。

You need to use re.search . 您需要使用re.search re.match only attempts to match starting at the beginning of the string. re.match仅尝试从字符串开头开始进行匹配。 However, re.search will search through the entire string looking for a substring that matches the pattern. 但是, re.search将搜索整个字符串以查找与模式匹配的子字符串。

>>> import re
>>> s = "bob2323"
>>> re.match(r'\d+', s)
>>> re.search(r'\d+', s)
<_sre.SRE_Match object at 0x7f4d19beb988>
>>> 

See search() vs. match() in the docs for more information 有关更多信息,请参见文档中的search()与match()

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

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