Regular Expression in PATINDEX That Matches [A-Z] EXCEPT for U

135 views Asked by At

I am trying to work out a Regular Expression to use in PATINDEX that will match a certain pattern (hence PATINDEX).

I need to match the first 3 characters exactly with 003 The 4th character can be any alpha character EXCEPT for U   I have this working for the 003 and A-Z

SELECT  PATINDEX('%[0][0][3][A-Za-z]%', '003A654')

I tried to negate Uu, but it didn't work, it still sees the pattern. When I check it on RegExr it doesn't see it as negating the U unless I put it into it's own group, but that doesn't work either.

SELECT  PATINDEX('%[0][0][3][A-Za-z^Uu]%', '003U654')
SELECT  PATINDEX('%[0][0][3][A-Za-z][^Uu]%', '003U654')

I know I can do something ugly like match the 003(alpha) using PATINDEX and add AND SUBSTRING('003U654',4,1) <> 'U' but I would prefer to do it cleaner if possible.

1

There are 1 answers

1
anubhava On BEST ANSWER

You can split your range into 2 and leave U and u out. Moreover [0] is same 0 so no need to use a character class for that.

Your regex be:

SELECT PATINDEX('%003[A-TV-Za-tv-z]%', '003A654')