python - 正则表达式最佳实践 : is it ok to use regex to match multiple phrases?

标签 python regex

我有一个简短短语列表,每个短语的长度不应超过 5 个单词,并且我想查看这些短语中是否有任何短语出现在特定文本中。

我想写这样的东西:

my_phrases = ['Hello world', 'bye world', 'something something'....]
my_regex = re.compile('|'.join(my_phrases))

my_iter = re.finditer(my_regex, text)

但我有点担心这(第 2 行)不被认为是一个好的做法。有人可以告诉我这是否可以做?如果不是,匹配文本中多个短语的最佳方法是什么?

最佳答案

我想说你的方法只错过了一件好的实践:处理原始短语列表中的特殊字符:想象列表是

['oh, really?', 'definitely!', 'no, never.']

那么你的正则表达式也会匹配“哦,真的是这样”,因为?意味着“y”成为可选的,它也会匹配“不,永无止境的故事”,因为“.”意思是“任何字符”。

为了使代码成为“最佳实践”,您需要将字符串传递给转义此类特殊字符的函数,幸运的是 re.escape 就是这样一个函数,因此您可以简单地使用它来映射所有字符串:

my_phrases = ['Hello world', 'bye world', 'something something'....]
my_regex = re.compile('|'.join(map(re.escape, my_phrases)))
my_iter = re.finditer(my_regex, text)

或者(更易读):

my_phrases = ['Hello world', 'bye world', 'something something'....]
my_phrases_escaped = map(re.escape, my_phrases)
my_regex = re.compile('|'.join(my_phrases_escaped))
my_iter = re.finditer(my_regex, text)

关于python - 正则表达式最佳实践 : is it ok to use regex to match multiple phrases?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28217385/

相关文章:

python - 我是否需要在 python 项目中跨模块共享记录器实例?

python - 将 Plotly 图像字节对象转换为 numpy 数组

python - 在 wxPython 中引发 wx.EVT_CLOSE 后如何阻止窗口关闭?

java - 如果单引号在 <xsl : or <XSL: 内,则正则表达式用单引号替换两次

正则表达式因 html 片段而失败

html - Perl - 按 "table"标签及其内容拆分 html 代码

python - 找不到 Jupyter notebook jt 命令

python - 如何在 for 循环中堆叠多个 pandas DataFrame

mysql - MySQL 8中无效的regexp

Ruby - 从字符串中删除模式