您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

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)
python 2022/1/1 18:29:37 有186人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶