What's a regex that matches all numbers except 1, 2 and 25?
Asked Answered
U

4

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.

Underproduction answered 28/8, 2014 at 16:16 Comment(4)
first what language are you using? and second how about sharing what you have tried so far?Uncharitable
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.Comatose
Actually regex won't match numbers it only matches characters. A seven digit character string will still be just an int.Properly
Does your script/language support negative constructs? if ( matched ) then failProperly
R
26

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

Republican answered 28/8, 2014 at 16:19 Comment(1)
then do us a favor and share what would be, to your eye, better/best tool for the task ;)Yam
I
4

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.

Infusible answered 28/8, 2014 at 16:20 Comment(0)
B
1
  (?!^1$|^2$|^25$)(^\d+$)

This should work for your case.

Bertie answered 28/8, 2014 at 16:38 Comment(0)
B
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)$/))`
Bad answered 28/8, 2014 at 16:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.