How To Match--but Not Capture--in Python Regular Expressions?
Solution 1:
That's a clever way indeed, but not-capturing doesn't mean removing it from match. It just mean, that it's not considered as an output group.
You should try to do something similar to the following:
match = re.search(r'(\w+)\s(?:D\.C\.), (\w\w)\W', location).groups()
This prints ('Washington', 'DC')
.
Note the difference between .group()
and .groups()
. The former gives you the whole string that was matched, the latter only the captured groups. Remember, you need to specify what you want to include in the output, not what you want to exclude.
Solution 2:
matches = re.search(r'(\w+\s)(?:D\.C\.)(, \w\w)(?=\W)', location).group(1,2)
match = ''.join(matches)
When it says it is "non-capturing", that means it won't make a separate captured group for it. The text "D.C." is still in the match. See http://docs.python.org/library/re.html#match-objects
Solution 3:
I'm late to this and the first two answers were great, but if by any chance you need a general regex for pulling cities out of a combination of cities, suffixes, states/provinces, and countries, but you know D.C. is an annoying special case, you might be able to use the following:
>>> import re
>>> city = re.compile(r'(\w+(?:\sD\.C\.)?), \w\w(?=\W)')
>>> location = "Washington D.C., DC, USA"
>>> re.search(city, location).group(1)
'Washington D.C.'
>>> location = "Vancouver, BC, Canada"
>>> re.search(city, location).group(1)
'Vancouver'
The D.C. part is made optional (as you don't always need it) in addition to being non-capturing (to save memory).
Post a Comment for "How To Match--but Not Capture--in Python Regular Expressions?"