我必须找到字符串在 # using regex in python 之前的任何地方都没有单词(作为单词边界) abc、def 或 ghi
他是 abc 但 # 不是 xyz - 不匹配
他很好#但是很小- 比赛
他可能会 ghi 但 # 不会 abc 会- 不匹配
他会帮忙,但#希望 def 能够到来- 比赛
他打算参加 vabc 但 # 不确定- 比赛
这是包含字符串的列表
l=["he is abc but # not xyz",
"he is good # but small",
"he might ghi but # not abc will",
"he will help but # hope for def to come",
"he is going for vabc but # not sure"]
Run Code Online (Sandbox Code Playgroud)
它应该打印
["he is good # but small", "he will help but # hope for def to come", "he is going for vabc but # not sure"]
Run Code Online (Sandbox Code Playgroud)
尝试在正则表达式中使用负前瞻概念
l=["he is abc but # not xyz",
"he is good # but small",
"he might ghi but # not abc will",
"he will help but # hope for def to come",
"he is going for vabc but # not sure"]
Run Code Online (Sandbox Code Playgroud)
但无法达到确切的结果
将我的评论转换为答案,以便未来的访问者可以轻松找到解决方案。
您可以使用这个正则表达式:
^(?![^#]*\b(?:abc|def|ghi)\b)[^#]*#.*
Run Code Online (Sandbox Code Playgroud)
正则表达式详细信息:
^: 开始(?![^#]*\b(?:abc|def|ghi)\b[^#]*#):如果在稍后的匹配中匹配 a 之前出现单词abcordef或 ,ghi则负向前视会使匹配失败#[^#]*:匹配 0 个或多个不存在的字符##: 匹配一个#.*: 之后匹配任何内容