'What's a regex that matches all numbers except 1, 2 and 25?
There's an input of strings that are composed of only digits, i.e., integer numbers. How can I write a regular expression that will accept all the numbers except numbers 1, 2 and 25?
I want to use this inside the record identification of BeanIO (which supports regular expressions) to skip some records that have specific values.
I reach this point ^(1|2|25)$
, but I wanted the opposite of what this matches.
Solution 1:[1]
Not that a regex is the best tool for this, but if you insist...
Use a negative lookahead:
/^(?!(?:1|2|25)$)\d+/
See it here in action: http://regexr.com/39df2
Solution 2:[2]
You could use a pattern like this:
^([03-9]\d*|1\d+|2[0-46-9]\d*|25\d+)$
Or if your regex engine supports it, you could just use a negative lookahead assertion ((?!…)
) like this:
^(?!1$|25?$)\d+$
However, you'd probably be better off simply parsing the number in code and ensuring that it doesn't equal one of the prohibited values.
Solution 3:[3]
(?!^1$|^2$|^25$)(^\d+$)
This should work for your case.
Solution 4:[4]
See this related question on Stack Overflow.
You shouldn't try to write such a regular expression since most languages don't support the complement of regular expressions.
Instead you should write a regex that matches only those three things: ^(1|2|25)$
- and then in your code you should check to see if this regex matches \d+
and fails to match this other one, e.g.:
`if($myStr =~ m/\d+/ && !($myStr =~ m/^(1|2|25)$/))`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Keith Thompson |
Solution 2 | informatik01 |
Solution 3 | vks |
Solution 4 | Peter Mortensen |