小编use*_*287的帖子

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

我有两个字符串:

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正在匹配.我错过了什么?

python regex

0
推荐指数
1
解决办法
758
查看次数

标签 统计

python ×1

regex ×1