Skip to main content
 首页 » 编程设计

python之使用 Python 的 re 模块匹配正则表达式组(带或)和特殊字符

2025年05月04日26zfyouxi

我正在尝试像下面的标题一样拆分字符串,然后匹配名称和任何附加信息,无论是在方括号/大括号中还是在破折号之后(常规、m/n 破折号、单杠)。

正则表达式对我来说似乎很好,我可以在其他正则表达式测试仪上测试它,但在使用 Python 运行时它不起作用。

发生了一些奇怪的事情。第一个虚线标题似乎匹配,但 addition_a 组不包含正确的字符串。此外,出于某种原因,任何特殊字符(如各种破折号)根本不匹配。脚本的编码是 utf-8,所以我假设原始正则表达式字符串中的破折号应该可以正常工作,但事实并非如此。

# -*- coding: utf-8 -*- 
import re 
titles = [ 
    'Spaced (News)', 
    'Angry Birds [Game]', 
    'Cheats - for all games', # dash 
    'Cheats – for all games', # ndash 
    'Cheats — for all games', # mdash 
    'Cheats ― for all games'  # horizontal bar 
] 
regex = re.compile(r'^(?P<name>.+)\s+(([-–—―]\s+(?P<addition_a>.+))|([\(\[](?P<addition_b>.+)[\)\]]))$') 
for title in titles: 
    data = {} 
    match = regex.match(title.strip()) 
    if match: 
        data['name'] = match.group('name') 
        try: 
            data['addition'] = match.group('addition_a') 
        except IndexError: 
            pass 
        try: 
            data['addition'] = match.group('addition_b') 
        except IndexError: 
            pass 
    print data 

输出:

{'addition': 'News', 'name': 'Spaces'} 
{'addition': 'Game', 'name': 'Angry Birds'} 
{'addition': None, 'name': 'Cheats'} 
{} 
{} 
{} 

请您参考如下方法:

使用 unicode 文字。否则,[-——――]匹配-、\xe2、\x80、\x93 , \xe2, \x80, \x94, \xe2, \x80 , \x95 而不是 -, –, —, —

# -*- coding: utf-8 -*- 
import re 
titles = [ 
    u'Spaced (News)', 
    u'Angry Birds [Game]', 
    u'Cheats - for all games', # dash 
    u'Cheats – for all games', # ndash 
    u'Cheats — for all games', # mdash 
    u'Cheats ― for all games'  # horizontal bar 
] 
regex = re.compile(ur'^(?P<name>.+)\s+(([-–—―]\s+(?P<addition_a>.+))|([\(\[](?P<addition_b>.+)[\)\]]))$') 
for title in titles: 
    match = regex.match(title.strip()) 
    if match: 
        data = {} 
        data['name'] = match.group('name') 
        data['addition'] = match.group('addition_a') or match.group('addition_b') 
        print data 

输出:

{'addition': u'News', 'name': u'Spaced'} 
{'addition': u'Game', 'name': u'Angry Birds'} 
{'addition': u'for all games', 'name': u'Cheats'} 
{'addition': u'for all games', 'name': u'Cheats'} 
{'addition': u'for all games', 'name': u'Cheats'} 
{'addition': u'for all games', 'name': u'Cheats'} 

>>> r'[–]' 
'[\xe2\x80\x93]' 
>>> re.findall(r'[–]', '–') 
['\xe2', '\x80', '\x93'] 
>>> re.findall(ur'[–]', u'–') 
[u'\u2013'] 
>>> print re.findall(ur'[–]', u'–')[0] 
–