8
votes

There's an input of Strings that are composed of only digits, i.e. integer numbers. How to write a regex 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 regex) to skip some records that have specific values.

I reach this point ^(1|2|25)$, but I wanted the opposite of what this matches.

4
first what language are you using? and second how about sharing what you have tried so far?Dalorzo
Why are you so intent on using a regex for this? It sounds like you should just do atoi() or similar and compare the actual numbers, or even just compare strings directly.Dolda2000
Actually regex won't match numbers it only matches characters. A seven digit character string will still be just an int.user557597
Does your script/language support negative constructs? if ( matched ) then failuser557597

4 Answers

17
votes

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

3
votes

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.

1
votes
  (?!^1$|^2$|^25$)(^\d+$)

This should work for your case.

0
votes

See this related question on stackoverflow.

You shouldn't try to write such a regular expression since most languages don't support the complement of regular expressions.

Instead what you should do is 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)$/))`