14

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ktulinho
  • 3,870
  • 9
  • 28
  • 35
  • 3
    first what language are you using? and second how about sharing what you have tried so far? – Dalorzo Aug 28 '14 at 16:17
  • 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 Aug 28 '14 at 16:18
  • Actually regex won't match `numbers` it only matches characters. A seven digit character string will still be just an int. –  Aug 28 '14 at 16:46
  • Does your script/language support negative constructs? `if ( matched ) then fail` –  Aug 28 '14 at 16:50

4 Answers4

25

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

Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • then do us a favor and share what would be, to your eye, better/best tool for the task ;) – ash17 Jun 24 '23 at 10:22
3

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.

informatik01
  • 16,038
  • 10
  • 74
  • 104
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
1
  (?!^1$|^2$|^25$)(^\d+$)

This should work for your case.

vks
  • 67,027
  • 10
  • 91
  • 124
0

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)$/))`
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
FrobberOfBits
  • 17,634
  • 4
  • 52
  • 86