Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
775 views
in Technique[技术] by (71.8m points)

regex - Regular Expression Opposite

Is it possible to write a regex that returns the converse of a desired result? Regexes are usually inclusive - finding matches. I want to be able to transform a regex into its opposite - asserting that there are no matches. Is this possible? If so, how?

http://zijab.blogspot.com/2008/09/finding-opposite-of-regular-expression.html states that you should bracket your regex with

/^((?!^ MYREGEX ).)*$/

, but this doesn't seem to work. If I have regex

/[a|b]./

, the string "abc" returns false with both my regex and the converse suggested by zijab,

/^((?!^[a|b].).)*$/

. Is it possible to write a regex's converse, or am I thinking incorrectly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Couldn't you just check to see if there are no matches? I don't know what language you are using, but how about this pseudocode?

if (!'Some String'.match(someRegularExpression))
    // do something...

If you can only change the regex, then the one you got from your link should work:

/^((?!REGULAR_EXPRESSION_HERE).)*$/

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...