英文:
Regex match a word, but not surrounded by specific words
问题
我正在寻找一个正则表达式语法,可以检测一个单词,但如果它被非常特定的单词包围,就不会被检测出来。
例如:
单词 "beautiful" 会被检测到,只要它出现在句子中。
但是,
如果单词 "beautiful" 被单词 "this" 和 "picture" 包围,它不会被检测到。例如:"我喜欢这个美丽的图片"。
谢谢你的帮助。
英文:
I'm looking for a regex syntax that would allow me to detect a word, but that doesn't it detect if it's surrounded by very specific words.
for example:
the word "beautiful" is detected, if only or in a sentence
BUT
the word "beautiful" is not detected if it's surrounded by the words "this" and "picture". For example: "I love this beautiful picture".
Thank you for your help
答案1
得分: 1
我理解这个问题的意思是,除非单词被两个其他单词包围,而且周围的单词完全匹配,否则应该找到该单词。这使得正则表达式比dinhit评论中的正则表达式稍微复杂一些,但我同意负向后视断言和负向前视断言是关键。我们只需要一个“或”来完成它,以及[^\w]术语来排除周围单词中的其他单词字符。
(?<!\bthis )\bbeautiful\b|\bbeautiful\b(?! picture\b)
在这里尝试一下:https://regex101.com/r/GzuVln/2
英文:
I understood the question to mean that the word should be found unless it is surrounded by both of the other words, and also that the surrounding words should match exactly. This makes the regex slightly more complicated than the one in dinhit's comment, but I agree that negative lookbehinds and negative lookaheads are the key. We just need an "or" to finish it off, and the [^\w] terms to exclude other word characters in the surrounding words.
(?<!\bthis )\bbeautiful\b|\bbeautiful\b(?! picture\b)
Try it out here: https://regex101.com/r/GzuVln/2
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论