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.
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.
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).
?= 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).
+: 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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With