How can I negate this regex?
I found a collection of words on this website about regular expressions. I tried number 5 and managed to match the opposite of what I need.
These should not be matched:
abba
anallagmatic
bassarisk
...
These should be matched:
acritan
aesthophysiology
amphimictical
...
This pattern matches the inverse:
([a-z])([a-z])21
Unfortunately, I do not know how to negate it. I read about this:
(?!([a-z])([a-z])21)
But it seems that simple nesting does not work. Is nesting of groups supported when using regular expressions?
What could it do?
Answer to Your Question
You have to get a little fancy with it:
^((?!([a-z])([a-z])32).)+$
Debuggex Demo
Some Hints
Since this is coming from regex golf puzzle 5 at http://regex.alf.nu/ , I'll give you a couple of hints.
First, some clarification for readers not familiar with these puzzles : this is a puzzle, based on xkcd comic 1313 . It's called "regex golf." You are given two lists and have to figure out how to match all elements in one but none in the other, using the shortest regex you can find. On the website in question, most of the puzzles have a pattern in one of the lists, and the goal is to figure out the rule that applies and either write a short regex applying that rule or, if it's shorter, a regex that ignores the rule but just happens to work. In this case, you want to match words that don't have an abba
(or itti
, or whatever) pattern in their letters.
Hint 1: This is shorter, because it replaces [az]
with S
:
^((?!(S)(S)32).)+$
Debuggex Demo
Hint 2: While both regexes above work, neither is by any means the shortest working regex for the puzzle. The shortest working regex is a "cheat" in that it doesn't literally match the pattern, but nonetheless discriminates correctly between lists.
This has been answered here:
How to negate the whole regex?
Or another idea is that you can do it in code. For example, in C#..
strin gtext = "abba";
Regex r = new Regex("([a-z])([a-z])21");
if(!r.IsMatch(text))
//Then do something
With ! you are saying the same that if Is Not Match
链接地址: http://www.djcxy.com/p/77002.html上一篇: 正则表达式只匹配整个单词
下一篇: 我怎样才能否定这个正则表达式?