I am trying to search a string in python using regex for a particular word that begins with a space and ends with a space after it. The string in question that I want to search is;
JAKARTA, INDONESIA (1 February 2017)
", INDONESIA ("
text = "JAKARTA, INDONESIA (1 February 2017)"
countryRegex = re.compile(r'^(,)(\s)([a-zA-Z]+)(\s)(\()$')
mo = countryRegex.search(text)
AttributeError: 'NoneType' object has no attribute 'group'
Once you remove the anchors (
^ matches the start of string position and
$ matches the end of string position), the regex will match the string. However, you may get
INDONESIA with a capturing group using:
See the regex demo.
match.group(1) will contain the value.
,\s*- a comma and zero or more whitespaces (replace
+if you want at least 1 whitespace to be present)
([a-zA-Z]+)- capturing group 1 matching one or more ASCII letters
\s*- zero or more whitespaces
import re text = "JAKARTA, INDONESIA (1 February 2017)" countryRegex = re.compile(r',\s*([a-zA-Z]+)\s*\(') mo = countryRegex.search(text) if mo: print(mo.group(1))
An alternative regex that would capture anything between
,+whitespace and whitespace+
See this regex demo. Here,
[^)]+? matches 1+ chars other than
) as few as possible.