正则表达式匹配某些模式或预定义字符串

use*_*287 0 python regex

我有两个字符串:

a = 'B E R L I N IS A CITY'
b = 'PARIS IS A CITY, TOO'
Run Code Online (Sandbox Code Playgroud)

我希望匹配第一个单词,以防它是单个空格或预定义的单词.

我提出的正则表达式(Python)是

regex = re.compile('^(?P<city>([a-z] )*|(paris )).*$', re.IGNORECASE)
print regex.match(a).group('city'), regex.match(b).group('city')
>>>> ('B E R L I N ', '')
Run Code Online (Sandbox Code Playgroud)

Paris没有匹配.但是当我转过正则表达式时,

regex = re.compile('^(?P<city>(paris )|([a-z] )*).*$', re.IGNORECASE)
print regex.match(a).group('city'), regex.match(b).group('city')
>>>> ('B E R L I N ', 'PARIS ')
Run Code Online (Sandbox Code Playgroud)

Paris正在匹配.我错过了什么?

Gum*_*mbo 5

"问题"是在重复零次时^([a-z] )*匹配字符串的开头.因此,正则表达式解释器不需要测试文字.PARIS …[a-z] paris 

使用+而不是+和它按预期工作:

^(?P<city>([a-z] )+|(paris )).*$
Run Code Online (Sandbox Code Playgroud)