tadasajon
tadasajon

Reputation: 14836

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?

Upvotes: 1

Views: 84

Answers (2)

Paul Bissex
Paul Bissex

Reputation: 1704

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.

Upvotes: 2

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

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

Upvotes: 3

Related Questions