正则表达式说明什么不匹配? [英] Regex that says what NOT to match?

查看:52
本文介绍了正则表达式说明什么不匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在正则表达式中匹配任何字符除了特定字符串(称为"for").

I’m wondering how to match any characters except for a particular string (call it "for") in a regex.

我在想可能是这样的:[^for]*——除了那行不通.

I was thinking maybe it was something like this: [^for]* — except that that doesn’t work.

推荐答案

我确定这是一个重复.

一种方法是用这样的前瞻开始你的模式:

One way is to start your pattern with a lookahead like this:

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

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

That can be written like this in any regex system worth bothering with:

(?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/&&⋯ 当您必须将这些知识构建到模式中时.

Now just put that in the front of your pattern, and add whatever else you’d like afterwords. That’s how you express the logic !/for/ && ⋯ when you have to built such knowledge into the pattern.

它类似于你如何构造 /foo/&&/bar/&&/glarch/ 当你必须把它放在一个单一的模式中,也就是

It is similar to how you construct /foo/ && /bar/ && /glarch/ when you have to put it in a single pattern, which is

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

这篇关于正则表达式说明什么不匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆