Python正则表达式:单词集的替代

发布于 2021-01-29 14:10:03

我们知道\ba\b|\bthe\b会匹配单词“ a ”或“ the ”,
我想构建一个正则表达式来匹配像这样的模式

的/一个/一个原因/原因

这意味着我要匹配s包含3个单词的字符串:

  • 的第一个单词s应为“ a ”,“ the ”或“ one
  • 第二个单词应该是“ 原因 ”或“ 原因
  • 的第三个字s应为“ ”或“

正则表达式\ba\b|\bthe\b|\bone\b \breason\b|reasons\b \bfor\b|\bof\b无济于事。

我怎样才能做到这一点?顺便说一句,我使用python。谢谢。

关注者
0
被浏览
183
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    正则表达式模块的一个有趣功能是命名列表。有了它,您就不必|在非捕获组中包括多个由分隔的选项。您只需要在列表之前定义列表,并通过名称在模式中引用它即可。例:

    import regex
    
    words = [ ['a', 'the', 'one'], ['reason', 'reasons'], ['for', 'of'] ]
    
    pattern = r'\m \L<word1> \s+ \L<word2> \s+ \L<word3> \M'
    p = regex.compile(pattern, regex.X, word1=words[0], word2=words[1], word3=words[2])
    
    s = 'the reasons for'
    
    print(p.search(s))
    

    即使此功能不是必需的,它也可以提高可读性。

    如果您|在之前加入项目,则可以通过re模块实现类似的功能:

    import re
    
    words = [ ['a', 'the', 'one'], ['reason', 'reasons'], ['for', 'of'] ]
    
    words = ['|'.join(x) for x in words]
    
    pattern = r'\b ({}) \s+ ({}) \s+ ({}) \b'.format(*words)
    
    p = re.compile(pattern, re.X)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看