繁体   English   中英

Python-为什么这个简单的正则表达式不起作用?

[英]Python - why doesn't this simple regex work?

下面的代码应该可以自我解释。 正则表达式很简单。 为什么不匹配?

>>> import re
>>> digit_regex = re.compile('\d')
>>> string = 'this is a string with a 4 digit in it'
>>> result = digit_regex.match(string)
>>> print result
None

或者,这可以工作:

>>> char_regex = re.compile('\w')
>>> result = char_regex.match(string)
>>> print result
<_sre.SRE_Match object at 0x10044e780>

为什么第二个正则表达式起作用,而不是第一个起作用?

re.match()所说的, If zero or more characters at the beginning of string match the regular expression pattern ...

在您的情况下,字符串开头没有任何数字\\d 但是对于\\w它在字符串的开头没有t

如果要使用相同的机制检查字符串中的数字,请在正则表达式中添加.*

digit_regex = re.compile('.*\d')

第二个找到匹配项,因为string以单词字符开头。 如果要在字符串中查找匹配项,请使用searchfindall方法(我也认为这是在注释中建议的)。 或更改您的正则表达式(例如.*(\\d).* ),并在结果上使用.groups()方法。

暂无
暂无

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

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