Location Regex - Python

How would you match locations (places) with regular expressions in python. It must match locations in the following format:

  • London, England, UK
  • Melbourne, VIC, Australia
  • Palo Alto, California, USA

I tried this, but it does not work:

re.findall(r'([A-Z][a-z]+ ([A-Z][a-z]+)?,)+',x)

EDIT:

ok, let me explain what i want. I have a huge wall with text. I need to find places like the above from the text. do not confirm.

Example:

text = """
..............................
..............................
London, ENG, United Kingdom...
..............................
"""
re.findall(r'<something>',x)
#['London, ENG, United Kingdom']

it should be able to match any format location Xxxx, XXX, Xxxxwith additional commas and optionally a few words

+4
source share
3 answers

re.split?

'London, ENG, United Kingdom or Melbourne, VIC, Australia or Palo Alto, CA USA'
>>> list(map(str.strip, re.split(',|or', x)))
['London', 'ENG', 'United Kingdom', 'Melbourne', 'VIC', 'Australia', 'Palo Alto', 'CA USA']
>>> list(map(str.strip, re.split('or', x)))
['London, ENG, United Kingdom', 'Melbourne, VIC, Australia', 'Palo Alto, CA USA']

, or, . str.split:

>>> list(map(str.strip, x.split('or')))
['London, ENG, United Kingdom', 'Melbourne, VIC, Australia', 'Palo Alto, CA USA']
  • list , Python 2.x.

UPDATE

>>> x = 'London, ENG, United Kingdom / Melbourne, VIC, Australia / Palo Alto, CA USA'
>>> re.findall(r'(?:\w+(?:\s+\w+)*,\s)+(?:\w+(?:\s\w+)*)', x)
['London, ENG, United Kingdom', 'Melbourne, VIC, Australia', 'Palo Alto, CA USA']
+2

() , :

locations = {"London, ENG, United Kingdom":True, "Melbourne, VIC, Australia":True...}

locations, , x .

( ):
, () , . , :

"London, ENG, United Kingdom" in text

, , :

locations = ["London, ENG, United Kingdom", "Melbourne, VIC, Australia",...]
...
for location in locations:
    for location in text:
        # do what you want here
+1

, , :

r'\w+, \w+, \w+'

@falsetru, . Thankyou @falsetru

+1
source

All Articles