简体   繁体   中英

How to strip all non-alphabetic characters (except hyphen) from string in SQL Server?

Select dbo.[RemoveNonAlphaNumExceptSub]('aAbc123-4def5678ghi90 jkl#^.\')
  • escaping '%[^a-z0-9-]%' returns aAbc123-4def5678ghi90jkl\\
  • before '%[-^a-z0-9]%' returns #.\\ adding in beginning, end they hyphen but it still gets stripped

How to strip all non-alphabetic characters from string in SQL Server?

Create Function [dbo].[RemoveNonAlphaNumExceptSub]( @Temp VarChar( max ) )
Returns VarChar( 1000 )
AS
Begin

    Declare @KeepValues as varchar( 50 )
    Set @KeepValues = '%[^a-z0-9]%'
    While PatIndex( @KeepValues, @Temp ) > 0
    Set @Temp = Stuff( @Temp, PatIndex( @KeepValues, @Temp ), 1, '' )

Return @Temp
End

Try escaping it by placing a backslash in front of the regex pattern like: '%[^a-z0-9\\-]%' .

Alternatively, you can place the hyphen as the first character in the pattern like '%[-^a-z0-9]%'

Feel free to refer to this post for more help , or refer to this post too .

这最终可以工作'%[^ a-z0-9-]%'

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