Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python Regex match exact word

Tags:

python

regex

I am trying to match different expressions for addresses:

Example: '398 W. Broadway'

I would like to match W. or E. (east) or Pl. for place ...etc

It is very simple using this regex

(W.|West) for example.

Yet python re module doesn't match anything when I input that

>>> a
'398 W. Broadway'
>>> x = re.match('(W.|West)', a)
>>> x
>>> x == None
True
>>> 
like image 667
Saher Ahwal Avatar asked Sep 11 '26 07:09

Saher Ahwal


2 Answers

re.match matches at the beginning of the input string.

To match anywhere, use re.search instead.

>>> import re
>>> re.match('a', 'abc')
<_sre.SRE_Match object at 0x0000000001E18578>
>>> re.match('a', 'bac')
>>> re.search('a', 'bac')
<_sre.SRE_Match object at 0x0000000002654370>

See search() vs. match():

Python offers two different primitive operations based on regular expressions: re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string (this is what Perl does by default).

like image 86
falsetru Avatar answered Sep 12 '26 21:09

falsetru


.match() constrains the search to begin at the first character of the string. Use .search() instead. Note too that . matches any character (except a newline). If you want to match a literal period, escape it (\. instead of plain .).

like image 40
Tim Peters Avatar answered Sep 12 '26 19:09

Tim Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!