LIKE predicate in its standard edition does not support regular expressions, though a number of implementations (in particular, Oracle) supposes their usage, expanding the standard.
However, Transact-SQL, besides standard wildcard characters ("%" and "_"), introduces pair of additional symbols which make LIKE predicate more flexible as a tool. These symbols are:
[ ] - a single symbol from a character set (for example, [zxy]) or a range ([a-z]) specified in square brackets. Thus, it is possible to list multiple ranges at once (for example, [0-9a-z]);
^ - which in combination with square brackets excludes from the search sample the characters listed in a set or a range.
Let's explain use of these symbols by examples.
Console
Execute
SELECT * FROM
(
SELECT'5%' name UNIONALL
SELECT'55'UNIONALL
SELECT'5%%'UNIONALL
SELECT'3%%'UNIONALL
SELECT'a5%%'UNIONALL
SELECT'abc'UNIONALL
SELECT'abc 5% cde'UNIONALL
SELECT'5c2e'UNIONALL
SELECT'C2H5OH'UNIONALL
SELECT'C25OH'UNIONALL
SELECT'C54OH'
) x
/* 1 */
--WHERE name LIKE'5%' -- begins with 5
/* 2 */
--WHERE name LIKE '5[%]' -- 5%
/* 3 */
--WHERE name LIKE '5|%' ESCAPE '|'-- 5%
/* 4 */
--WHERE name LIKE '%5|%%' ESCAPE '|' -- 5% in any place of a string
/* 5 */
--WHERE name LIKE '[0-9][a-zA-Z]%' -- the first is a digit, the second is a letter
/* 6 */
--WHERE name LIKE '[a-z][0-9]%' -- the first is a letter, the second is a digit
/* 7 */
--WHERE name LIKE '[^0-9]%' -- begins with not a digit
/* 8 */
--WHERE name LIKE '%[02468]%' -- contains an even digit
/* 9 */
--WHERE name LIKE '%[02468][13579]%' -- a combination even-odd
In the given query some data are generated, for search over which the LIKE predicate is used. Nine examples is accordingly 9 commented (--) WHERE clauses. For check of results of executing of above query on the site, erase preliminary the comment for one of the lines beginning with WHERE. For those who cannot use a site, I shall present the results of executing these examples below.
1. All the strings, which begin with 5:
name
5%
55
5%%
5c2e
2. Searching of the string '5%'. The character in brackets is perceived as a usual single symbol:
name
5%
3.Other solution which is similar to the second one, but it is using the ESCAPE clause, specifying that it is necessary to perceive "%" as an usual symbol.
4. Searching of the substring '5%' being at any place in the string:
name
5%
5%%
a5%%
abc 5% cde
5. Searching of a string in which the first symbol is a digit, but the second one is a letter:
name
5c2e
6. Searching of a string in which the first symbol is a letter, and the second one is a digit. A variant for case-independent comparisons:
name
a5%%
C2H5OH
C25OH
C54OH
7. Searching of a string which begins not with digit:
name
a5%%
abc
abc 5% cde
C2H5OH
C25OH
C54OH
8. Searching of a string which contains even digit:
name
5c2e
C2H5OH
C25OH
C54OH
9. Searching of a string which contains successively going even and odd digits: