Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pattern match in SQL Server using regular expressions

I am trying to identify these kind of patterns in a SQL Server (2019) column:

78878001

1-1321-32

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

1321-12

121-5489-19

403-3-XXXXX

The rules are:

  • only numbers
    OR
  • only numbers and hyphens (at least one hyphen one but no specific number of them)
    OR
    numbers, hyphens and letter X

I tried this:

    SELECT * FROM [TABLE1] WHERE [Part no] like  '[0-9]%-%'

But it returns some incorrect values like:

  1. 702-3-01960 09150006125

700-3-02474 Arkds 4787-PA-51H-99999

>Solution :

If you’re using at least SQL Server 2012, I think you could solve this with try_parse. Using your data as an example:

create table #testing1 (val varchar(100))

INSERT INTO #testing1 
VALUES
('78878001'),
('1-1321-32'),
('1321-12'),
('702-3-01960 09150006125'),
('700-3-02474 Arkds 4787-PA-51H-99999'),
('121-5489-19'),
('403-3-XXXXX')

select * 
from #testing1
where try_parse(replace(replace(val, '-', ''), 'X', '') AS int) is not null
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading