正则表达式说什么不匹配?

标签 regex regex-negation

我想知道如何在正则表达式中匹配特定字符串(称为“for”)之外的任何字符。

我在想也许是这样的:[^for]* - 但那不起作用。

最佳答案

我确信这是一个骗局。

一种方法是通过如下所示的前瞻来开始您的模式:

(?=\A(?s:(?!for).)*\z)

在任何值得关注的正则表达式系统中都可以这样写:

(?x)            # turn /x mode on for commentary & spacing
(?=             # lookahead assertion; hence nonconsumptive
    \A          # beginning of string
    (?s:        # begin atomic group for later quantification
                        # enable /s mode so dot can cross lines    
        (?! for )       # lookahead negation: ain't no "for" here
        .               # but there is any one single code point
    )           # end of "for"-negated anything-dot
    *           # repeat that group zero or more times, greedily
    \z          # until we reach the very end of the string
)               # end of lookahead

现在只需将其放在模式的前面,然后在后添加您想要的任何其他内容。当您必须将此类知识构建到模式中时,这就是您表达逻辑 !/for/&& ⋯ 的方式。

这类似于当您必须将其放入单个模式时构建 /foo/&&/bar/&&/glarch/ 的方式,即

(?=\A(?s:.)*foo)(?=\A(?s:.)*bar)(?=\A(?s:.)*glarch)

关于正则表达式说什么不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5929732/

相关文章:

regex - 使用 Sublime Text 确保 LaTeX 文档中每行一个句子

regex - 正则表达式选择特定文本之前和之前的所有内容

c# - 如何通过正则表达式设置第一个字符?

正则表达式在特定位置的模式中找不到子字符串

c++ - 正则表达式 - 匹配后面没有特定模式的字符

php - 如何使用正则表达式在最后一次模式出现后捕获字符?

javascript - 如何使用正则表达式提取正文内容

regex - 当文本没有 "[^<]*<\\?"时,为什么正则表达式 "<"表现出指数时间?

regex - 在 Shiny 中使用 textOutput() 在单独的行上打印句子

正则表达式 - 将文本从一个街道号码匹配到下一个街道号码的模式