简体   繁体   中英

python Regex match exact word

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

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

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

withWithout = raw_input("Enter with or without: \n")
if re.match('with|without', withWithout):
    print "You enterd :", withWithout, "So I will DO!", withWithout
elif not re.match('with|without', withWithout):
    print " Error! you can only enter with or without ! "    
sys.exit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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