我通常很擅长使用正则表达式,但我在这个方面遇到了困难。我需要一个与术语 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/