问题
When I am searching for a string ending with one or two numbers, I am using the following pattern:
WHERE MyString LIKE 'ABC[0-9]'
OR MyString LIKE 'ABC[0-9][0-9]'
Is there a way to express my intent in one single equivalent pattern?
回答1:
If LIKE
supported regex quantifier syntax, you would do:
LIKE 'ABC[0-9]{1,2}'
However, according to the spec it does not.
If you do not want to use the regular expression functions, then you are stuck with what you have.
回答2:
You can use regular expressions with SQLServer.
Then your expression will become something like:
where dbo.RegexMatch( MyString, N'^ABC[0-9]{1,2}$' )
回答3:
One way, although there is not much wrong with the 2 ORs
(Remove '??' +
to skip values that are just 1 or 2 digits)
;with T(f) as (
select 'xxxxxxxxx' union
select 'xxxxxxxx6' union
select 'xxxxxxx66' union
select 'xxxxxx666' union
select 'xxxxx6666' union
select 'xxxxx666x' union
select '66' union
select '6' union
select ''
)
select
*
from
T
where
patindex('%[^0-9]%', reverse(right('??' + f, 3))) > 1
>>
f
6
66
xxxxxxx66
xxxxxxxx6
回答4:
How about something like this?
WHERE SUBSTRING(MyString, 4, 2) NOT LIKE '%[^0-9]%'
来源:https://stackoverflow.com/questions/8478775/how-to-describe-strings-ending-with-one-or-two-numbers-in-one-like-pattern