开发者

Regex that says what NOT to match?

开发者 https://www.devze.com 2023-03-04 21:37 出处:网络
I’m wondering how to match any characters except for a particular string (call it \"for\") ina regex.

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

I was thinking maybe it was somethi开发者_开发问答ng like this: [^for]* — except that that doesn’t work.


I’m sure this a dup.

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

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.

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)


^(?!for$).*$

matches any string except for.

^(?!.*for).*$

matches any string that doesn't contain for.

^(?!.*\bfor\b).*$

matches any string that doesn't contain for as a complete word, but allows words like forceps.


You can try to check whether the string matches for, and negate the result, in whatever language you use (e.g. if (not $_ =~ m/for/) in Perl)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号