简体   繁体   中英

How to get this using regular expressions in sql server 2005?

Please I need your help.

With regular expressions in SQL Server 2005 i get the house number of a postal address. Everything works ok. But I have problems with some directions.

For example, I have the address Florecita Terrace 1746-B floor 3 , the number of home you get is 1746-B , but the same address can be written as follows: Florecita Terrace 1746 B floor 3 and in this direction get the house number 1746 and lose the letter B because it is separate, not united as before by "-"

What I have to change my query to obtain 1746 B ?

This get (the house number):

Florecita Terrace 1746 B floor 3 | **1746**

This need to get (the house number):

Florecita Terrace 1746 B floor 3 | **1746 B**

This is the query I use:

declare @address table (address varchar(100))
insert into @address
    select 'Florecita Terrace 1746 B floor 3' union
    select 'Florecita Terrace 1746-B blablabla' union
    select 'Street Flor 4141' 

select  
     address,
     --patindex('%[0-9]%', address) as 'start',
     --charindex(space(1), address + space(1), patindex('%[0-9]%', address)) - (patindex('%[0-9]%', address)) as 'length',
    case 
        when patindex('%[^0-9]%' , address) > 0
                then substring(address, patindex('%[0-9]%', address), charindex(space(1), address + space(1), patindex('%[0-9]%', address)) - 
                                (patindex('%[0-9]%', address)))
        else address
    end as 'numeric'
from @address

Thank you very much for your help!

You can get SQL Server to use full-featured regular expressions if you enable CLR and add a .NET CLR assembly that creates a wrapper for the .NET Regular Expression procedures. A good example that you don't have to build for yourself in Visual Studio can be found here .

declare @address table (address varchar(100))
insert into @address
    select 'Florecita Terrace 1746 B floor 3' union
    select 'Florecita Terrace 1746-B blablabla' union
    select 'Street Flor 4141' 

select  
     address,
     --patindex('%[0-9]%', address) as 'start',
     --charindex(space(1), address + space(1), patindex('%[0-9]%', address)) - (patindex('%[0-9]%', address)) as 'length',
    case 
        when patindex('%[^0-9]%' , address) > 0
                then substring(address, patindex('%[0-9]%', address), charindex(space(1), address + space(1), patindex('%[0-9]%', address)) +(case when address not like ('%-%') then 2 else 1 end) - 
                                (patindex('%[0-9]%', address)))
        else address
    end as 'numeric'
from @address

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM