Home > Software design >  Pattern match in SQL Server using regular expressions
Pattern match in SQL Server using regular expressions

Time:01-14

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

78878001

1-1321-32

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

CodePudding user response:

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
  •  Tags:  
  • Related