Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex gotcha

Tags:

python

regex

Could you explain me why the first regex doesn't match?

Python 2.7.1 (r271:86832, Jun 16 2011, 16:59:05) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
>>> import re
>>> re.match(r'\d','.0')
>>> re.match(r'.\d','.0')
<_sre.SRE_Match object at 0x109adbd30>
like image 283
Andrei Avatar asked Apr 27 '26 10:04

Andrei


1 Answers

re.match() tries to match from the beginning of the string.

Use re.search() instead if you want to locate a match anywhere in the string.

PS: You might want to escape the ., because it's a metacharacter that matches any1 character (so x0 would match your second example).

>>> re.match(r'\.\d', 'x0')
>>> re.match(r'.\d', 'x0')
<_sre.SRE_Match object at 0x01F67138>

1 except newlines, unless re.DOTALL is used.

like image 185
NullUserException Avatar answered Apr 28 '26 23:04

NullUserException