python - 匹配一个单词但仅当另一个单词不出现时的正则表达式?

标签 python regex

我通常很擅长使用正则表达式,但我在这个方面遇到了困难。我需要一个与术语 cbd 匹配的正则表达式,但如果短语 central Business District 出现在搜索字符串中的任何地方,则不需要。或者,如果这太困难,至少匹配 cbd(如果短语 central Business District 没有出现在术语 cbd 之前的任何地方) 。只有cbd部分应该作为结果返回,所以我使用lookaheads/lookbehinds,但我一直无法满足要求...

输入示例:
好的 任何含有 CBD 的产品都将受到监管。
BAD    位于中央商务区 (CBD) 内的特性将受到监管

我已经尝试过:

  • (?!中央商务区)cbd
  • (.*(?!中央商务区).*)cbd

这是在 Python 3.6+ 中使用 re 模块实现的。

我知道用几行代码很容易完成,但是我们在数据库中有一个正则表达式字符串列表,我们正在使用该列表在语料库中搜索包含数据库中任何一个正则表达式字符串的文档。最好避免将任何关键字硬编码到脚本中,因为这样我们的其他开发人员就不清楚这些匹配项来自哪里,因为他们无法在数据库中看到它。

最佳答案

使用 PyPi 正则表达式

import regex
strings = [' I need a regular expression that matches the term cbd but not if the phrase central business district appears anywhere else in the search string.', 'I need cbd here.']
for s in strings:
  x = regex.search(r'(?<!central business district.*)cbd(?!.*central business district)', s, regex.S)
  if x:
    print(s, x.group(), sep=" => ")

结果:我这里需要 cbd。 => cbd。请参阅Python code .

说明

--------------------------------------------------------------------------------
  (?<!                     look behind to see if there is not:
--------------------------------------------------------------------------------
    central business         'central business district'
    district
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
  )                        end of look-behind
--------------------------------------------------------------------------------
  cbd                      'cbd'
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
    central business         'central business district'
    district
--------------------------------------------------------------------------------
  )                        end of look-ahead

关于python - 匹配一个单词但仅当另一个单词不出现时的正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64742598/

相关文章:

python - 为什么python对范围不严格?

python - 字符串到带小数秒的日期时间,在 Google App Engine 上

C# 正则表达式可选匹配

regex - 提取字符向量中两个特定单词之间的所有单词

regex - 调用字符串 "a?c"的正则表达式无效?

python - 基于另一列的滚动平均值

python - 为什么在 DataFrame 上应用函数(使用 "apply")比在 Series 上应用函数快得多?

python - 我想将views.py中获得的值传递给forms.py

php - PHP 正则表达式中的 ^$ 和 $^ 是否相同?

php - 函数 eregi() 已弃用