当前位置: 动力学知识库 > 问答 > 编程问答 >

Python - why doesn't this simple regex work?

问题描述:

This code below should be self explanatory. The regular expression is simple. Why doesn't it match?

>>> 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

Alternatively, this works:

>>> char_regex = re.compile('\w')

>>> result = char_regex.match(string)

>>> print result

<_sre.SRE_Match object at 0x10044e780>

Why does the second regex work, but not the first?

网友答案:

The second finds a match because string starts with a word character. If you want to find matches within the string, use the search or findall methods (I see this was suggested in a comment too). Or change your regex (e.g. .*(\d).*) and use the .groups() method on the result.

网友答案:

Here is what re.match() says If zero or more characters at the beginning of string match the regular expression pattern ...

In your case the string doesn't have any digit \d at the beginning. But for the \w it has t at the beginning at your string.

If you want to check for digit in your string using same mechanism, then add .* with your regex:

digit_regex = re.compile('.*\d')
分享给朋友:
您可能感兴趣的文章:
随机阅读: