Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using RegEx in SQL Server

I'm looking how to replace/encode text using RegEx based on RegEx settings/params below:

RegEx.IgnoreCase = True      RegEx.Global = True      RegEx.Pattern = "[^a-z\d\s.]+"    

I have seen some examples on RegEx, but confused as to how to apply it the same way in SQL Server. Any suggestions would be helpful. Thank you.

like image 308
Control Freak Avatar asked Jan 19 '12 15:01

Control Freak


People also ask

Can we use RegEx in SQL Server?

Regular expressions are a concise and flexible notation for finding and replacing patterns of text. A specific set of regular expressions can be used in the Find what field of the SQL Server Management Studio Find and Replace dialog box.

What does RegEx mean in SQL?

A Regular Expression is popularly known as RegEx, is a generalized expression that is used to match patterns with various sequences of characters. A RegEx can be a combination of different data types such as integer, special characters, Strings, images, etc.


1 Answers

You do not need to interact with managed code, as you can use LIKE:

CREATE TABLE #Sample(Field varchar(50), Result varchar(50)) GO INSERT INTO #Sample (Field, Result) VALUES ('ABC123 ', 'Do not match') INSERT INTO #Sample (Field, Result) VALUES ('ABC123.', 'Do not match') INSERT INTO #Sample (Field, Result) VALUES ('ABC123&', 'Match') SELECT * FROM #Sample WHERE Field LIKE '%[^a-z0-9 .]%' GO DROP TABLE #Sample 

As your expression ends with + you can go with '%[^a-z0-9 .][^a-z0-9 .]%'

EDIT:
To make it clear: SQL Server doesn't support regular expressions without managed code. Depending on the situation, the LIKE operator can be an option, but it lacks the flexibility that regular expressions provides.

like image 122
Rubens Farias Avatar answered Oct 21 '22 07:10

Rubens Farias