简体   繁体   中英

Python regex capturing & AttributeError: 'NoneType' object has no attribute 'group'

I want to capture the word "Avenue" in "Bukit Batok Avenue 3":

street_name = "Bukit Batok Avenue 3"
m = re.compile(r'(\S*?)\s\d$', re.IGNORECASE).search(street_name).group(1)

Group(1) doesn't work as the following is returned:

AttributeError: 'NoneType' object has no attribute 'group'

Or it would be cool to code the regex so that the word (Avenue) before a number(3) is captured, is that possible?

You can match the last word using this regex:

>>> import re
>>> re.search(r'(\w+)\s*\d$', "Bukit Batok Avenue 3", re.I)
<_sre.SRE_Match object; span=(12, 20), match='Avenue 3'>
>>> re.search(r'(\w+)\s*\d$', "Bukit Batok Avenue 3", re.I).group(1)
'Avenue'

Without using group() over Match object:

>>> import re
>>> re.findall(r'(\w+)\s*\d$', "Bukit Batok Avenue 3", re.I)
['Avenue']
>>> re.findall(r'(\w+)\s*\d$', "Bukit Batok Avenue 3", re.I)[0]
'Avenue'

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