Skip to content
Advertisement

PATINDEX Number/range of wildcard characters

In regex we have syntax for occurrence of any characters between ‘a’ and ‘b’ that goes like this:

/a.{5,15}b/

but we were able to specify minimum of characters between them (5) and maximum (15).

Is there any equivalent to specify range of wildcard characters in MsSQL for PATINDEX? We have % symbol for any characters but without minimum or limit, and _ symbol for just one wildcard character.

Advertisement

Answer

No, there isn’t. But you can do a brute force approach — which I will limit to 1-3 characters:

where col like '%a_b%' or
      col like '%a__b%' or
      col like '%a___b%'

The '_' wildcard matches exactly one character. You might actually want '[^ab] instead, so the end characters are not allowed.

If 'a' and 'b' only occur once in the string (and are not allowed “in-between”), you could use charindex():

where charindex('b', col) - charindex('a', col) between 1 + 1 and 3 + 1
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement