Xiaoyu Lu
Xiaoyu Lu

Reputation: 3570

SQL Server : how to remove leading/trailing non-alphanumeric characters from string?

I am using SQL Server 2008, and try to sanitize a list of urls.

Some existing examples of texts:

www.google.com
'www.google.com'
/www.google.com
www.google.com/

Ideally I can strip any leading/trailing non-alphanumeric characters so the four would give out the same output as

www.google.com

Upvotes: 1

Views: 526

Answers (3)

Zorkolot
Zorkolot

Reputation: 2017

You should be able to use Substring. Calculating length can be tricky:

DECLARE @temp TABLE (val varchar(100))
INSERT INTO @temp VALUES
 ('www.google.com'),('''www.google.com'''),('/www.google.com'),('www.google.com/'),('[www.google.com];')

SELECT SUBSTRING(val
                ,PATINDEX('%[a-zA-Z0-9]%', val) --start at position
                ,LEN(val) + 2 - PATINDEX('%[a-zA-Z0-9]%', val) 
                  - PATINDEX('%[a-zA-Z0-9]%', REVERSE(val)) --length of substring
                ) AS [Result]
  FROM @temp

Produces output:

Result
--------------
www.google.com
www.google.com
www.google.com
www.google.com
www.google.com

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269503

Well, if you know they are only at the beginning and end, you can do:

with t as (
      select *
      from (values ('www.google.com'), ('''www.google.com'''), ('/www.google.com')) v(text)
     )
select t.text, v2.text2
from t cross apply
     (values (stuff(t.text, 1, patindex('%[a-zA-Z0-9]%', t.text) - 1, ''))
     ) v(text1) cross apply
     (values (case when v.text1 like '%[^a-zA-Z0-9]'
                   then stuff(v.text1, len(text) + 1 - patindex('%[a-zA-Z0-9]%', reverse(v.text1)), len(v.text1), '')
                   else v.text1
              end)
     ) v2(text2);

Here is a db<>fiddle.

Upvotes: 2

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

Why not just use replace() ?:

SELECT REPLACE(REPLACE(col, '''', ''), '/', '')

Upvotes: 0

Related Questions