Regex for *either or both* of last two characters are not digits?

Viewed 41

I can't figure out the proper regular expression for this... Most of my data ends with digits as the last two characters. A subset ends with where either one or both of the last two are non-digits. So xyz99 is normal and I'm able to find those records with "*[0-9][0-9]$". If I change that to "*[^0-9][^0-9]$" then I get records where both are non-digits.

I don't know regex well enough to match all of the following with a single regex: xy9z, xyz9, xyzw, but not matching xyz99.

I prefer a single regex, but (already know how to and) can work-around with multiple.

Thanks for any help.

4 Answers

[^\d]$|[^\d].$

should do the trick

https://regex101.com/r/PsZxLj/2

It matches anything that doesn't end in a digit OR anything where the 2nd to last character isn't a digit. Lots of ways to do this, but pick one that is easy for you to read and maintain. :) Good luck!

Something like this should do it:

(?:\d[^\d]|[^\d].)$

You could use a negative lookahead (?!...).

(?![0-9]{2}).{2}$

This will first make sure that [0-9]{2} (2 digits) does not match. Then proceeds to match the remaining regex, which matches any 2 characters .{2} followed by the end of the string $.

regex diagram
Regexper

Thank you all for the quick and helpful responses. A couple of the references above that start with "(?" are beyond what I understand so far. But the "or" operator is what I was missing. Here is what I ended up using (and it worked): select * from mytable where regexp_like( myfield, '.*([^0-9]|[^0-9][0-9])$' );

Related