Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a dash to pattern matching

Tags:

sql-server

This works:

select Name
from Table
WHERE Name like '%[^0-9A-Za-z]%'

But now I need to add the dash character to the criteria as well.

like image 580
Phillip Senn Avatar asked May 24 '13 19:05

Phillip Senn


People also ask

How do you match a hyphen in regex in Perl?

The * is the zero-or-more repetition specifier. Now you should understand why this pattern does not match a hyphen: it matches zero-or-more of characters that is either a whitespace or a word character. If you want to match a hyphen, then you can include it into the character class.

Which clause is used for pattern matching?

LIKE clause is used to perform the pattern matching task in SQL. A WHERE clause is generally preceded by a LIKE clause in an SQL query.

Which SQL operator is used for pattern matching?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

How is pattern matching done?

SQL pattern matching allows you to search for patterns in data if you don't know the exact word or phrase you are seeking. This kind of SQL query uses wildcard characters to match a pattern, rather than specifying it exactly. For example, you can use the wildcard "C%" to match any string beginning with a capital C.


2 Answers

use

...ESCAPE '\'

e.g.

WHERE Name like '%[^0-9A-Za-z\-]%' ESCAPE '\'

to have the final "-" treated as a literal.

like image 82
davek Avatar answered Oct 04 '22 17:10

davek


Unless it's part of a range the hyphen is not a special character in LIKE patterns, so you can just add it to your pattern, e.g.:

select 
        [char]
from
    (
    select 'a' as 'char' union 
    select '-' union 
    select '$' union
    select '7'
    ) dt
where 
    [char] like '%[^A-Za-z0-9-]%'
like image 20
Pondlife Avatar answered Oct 04 '22 18:10

Pondlife