努力创建正确的正则表达式

  1. 我尝试为每个“单词”(小写或大写)进行匹配:(
    单词|WORD)

  2. 前后不能有任何字符或数字:
    (?<![^a-zA-Z0-9]) (word|WORD) (?![^a-zA-Z0-9])

  3. 如果“word”位于字符串的开头或结尾:
    ^| (?<![^a-zA-Z0-9])(字|WORD)(?![^a-zA-Z0-9]) |$

它根本不起作用,有什么建议吗?


UYOU
浏览 123回答 2
2回答

茅侃侃

您可能正在寻找import retext = "123 Lorem ipsum dolor sit amet, word WORD WoRd consetetur sadipscing elitr, sed diam 123"pattern = re.compile(r'\bword\b', re.IGNORECASE)for word in pattern.finditer(text):&nbsp; &nbsp; print(word.group(0))这会产生wordWORDWoRd\b是缩写形式(?:(?=\w)(?<!\w)|(?<=\w)(?!\w))其中读到(?=\w)(?<!\w) # positive lookahead making sure there's a word character coming&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # negative lookbehind making sure theres' n word characte preceding|&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# or(?<=\w)(?!\w) # the other way round所以,是的(?:(?=\w)(?<!\w)|(?<=\w)(?!\w))word(?:(?=\w)(?<!\w)|(?<=\w)(?!\w))会产生与上面相同的匹配,但似乎有点不可读。

qq_花开花谢_0

(?<![^a-zA-Z0-9]) 是双重否定。您是说,如果主表达式之前的字符不在 [a-zA-Z0-9] 中,则它不应该匹配,也就是说,只有当该字符在 [a-zA-Z0-9] 中时,它才能匹配。只需删除 ^: (?<![a-ZA-Z0-9])。您使用的字符串边界 ^ 和 $ 在这里会令人困惑,但如果您使用负向后查找和负向前查找,则不需要它们。因此,切换到(?<![a-zA-Z0-9])(word|WORD)(?![a-zA-Z0-9])。也就是说,@user3783243 关于 \b 的评论是一个更好的选择。\b 是一个“单词边界”,它准确地代表了您要捕获的内容。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python