Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 578
ktulinho Avatar asked Aug 28 '14 16:08

ktulinho


People also ask

How do you match everything except with regex?

How do you ignore something in regex? To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

How do I match a range of numbers in regex?

With regex you have a couple of options to match a digit. You can use a number from 0 to 9 to match a single choice. Or you can match a range of digits with a character group e.g. [4-9]. If the character group allows any digit (i.e. [0-9]), it can be replaced with a shorthand (\d).

What does ?= Mean in regular expression?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

Which regex matches one or more digits?

+: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.


2 Answers

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

like image 151
Joseph Silber Avatar answered Sep 20 '22 11:09

Joseph Silber


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.

like image 38
p.s.w.g Avatar answered Sep 19 '22 11:09

p.s.w.g