Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用改变组顺序的python正则表达式组解析文本_Python_Regex - Fatal编程技术网

使用改变组顺序的python正则表达式组解析文本

使用改变组顺序的python正则表达式组解析文本,python,regex,Python,Regex,我想像这样解析地名: à : Paris (France) 但在美国经常遇到这样的地方 à : Boston (MA) (États-Unis) 我试着这样分析它: place='à : (?P<city>.+) (\((?P<country>.+)\)|(\((?P<state>.+)\) \((?P<country>.+)\)))' place='a:(?P.+)(\(?P.+)\)(\(?P.+)\(?P.+)\(?P.+)\)'

我想像这样解析地名:

à : Paris (France)
但在美国经常遇到这样的地方

à : Boston (MA) (États-Unis)
我试着这样分析它:

place='à :  (?P<city>.+) (\((?P<country>.+)\)|(\((?P<state>.+)\) \((?P<country>.+)\)))'
place='a:(?P.+)(\(?P.+)\)(\(?P.+)\(?P.+)\(?P.+)\)'
但它似乎不起作用,超出了我目前对初学者的理解


如何处理此问题?

您可以使用量词
使状态组成为可选的:

à : (?P<city>\S+) (?:\((?P<state>\S+)\) )?\((?P<country>\S+)\)
#                 ^^^                   ^^
a:(?P\S+?:\(?P\S+)?\(?P\S+)
#                 ^^^                   ^^

在这种情况下,它将同时匹配:

à : (?P<city>\S+) \((?P<state>\S+)\) \((?P<country>\S+)\)
a:(?P\S+)\(?P\S+)\(?P\S+)

a:(?P\S+)\(?P\S+)
à : (?P<city>\S+) \((?P<country>\S+)\)