Regex that says what NOT to match?

Deadly 提交于 2019-12-22 12:37:17

问题


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 something like this: [^for]* — except that that doesn’t work.


回答1:


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)



回答2:


^(?!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.




回答3:


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)



来源:https://stackoverflow.com/questions/5929732/regex-that-says-what-not-to-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!