侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

SqlServer类似正则表达式的字符处理问题

数据库  /  管理员 发布于 5年前   323

SQL Serve提供了简单的字符模糊匹配功能,比如:like, patindex,不过对于某些字符处理场景还显得并不足够,日常碰到的几个问题有:

1. 同一个字符/字符串,出现了多少次

2. 同一个字符,第N次出现的位置

3. 多个相同字符连续,合并为一个字符

4. 是否为有效IP/身份证号/手机号等 

一. 同一个字符/字符串,出现了多少次

同一个字符,将其替换为空串,即可计算

declare @text varchar(1000)declare @str varchar(10)set @text = 'ABCBDBE'set @str = 'B'select len(@text) - len(replace(@text,@str,''))

同一个字符串,仍然是替换,因为是多个字符,方法1替换后需要做一次除法;方法2替换时增加一个字符,则不需要

--方法1declare @text varchar(1000)declare @str varchar(10)set @text = 'ABBBCBBBDBBBE'set @str = 'BBB'select (len(@text) - len(replace(@text,@str,'')))/len(@str)--方法2declare @text varchar(1000)declare @str varchar(10)set @text = 'ABBBCBBBDBBBE'set @str = 'BBB'select len(replace(@text,@str,@str+'_')) - len(@text)

二. 同一个字符/字符串,第N次出现的位置

SQL SERVER定位字符位置的函数为CHARINDEX:

CHARINDEX ( expressionToFind , expressionToSearch [ , start_location ] )

可以从指定位置起开始检索,但是不能取第N次出现的位置,需要自己写SQL来补充,有以下几种思路:

1. 自定义函数, 循环中每次为charindex加一个计数,直到为N

if object_id('NthChar','FN') is not null  drop function NthcharGOcreate function NthChar(@source_string as nvarchar(4000), @sub_string  as nvarchar(1024),@nth      as int) returns int as begin   declare @postion int   declare @count  int   set @postion = CHARINDEX(@sub_string, @source_string)   set @count = 0   while @postion > 0   begin     set @count = @count + 1     if @count = @nth     begin       break     end    set @postion = CHARINDEX(@sub_string, @source_string, @postion + 1)   End   return @postion end GO--select dbo.NthChar('abcabc','abc',2)--4

2. 通过CTE,对待处理的整个表字段操作, 递归中每次为charindex加一个计数,直到为N

if object_id('tempdb..#T') is not null  drop table #Tcreate table #T(source_string nvarchar(4000))insert into #T values (N'我们我们')insert into #T values (N'我我哦我')declare @sub_string nvarchar(1024)declare @nth    intset @sub_string = N'我们'set @nth = 2;with T(source_string, starts, pos, nth) as (  select source_string, 1, charindex(@sub_string, source_string), 1 from #t  union all  select source_string, pos + 1, charindex(@sub_string, source_string, pos + 1), nth+1 from T  where pos > 0)select   source_string, pos, nthfrom Twhere pos <> 0 and nth = @nthorder by source_string, starts--source_string  pos  nth--我们我们  3  2

3. 借助数字表 (tally table),到不同起点位置去做charindex,需要先自己构造个数字表

--numbers/tally tableIF EXISTS (select * from dbo.sysobjects where id = object_id(N'[dbo].[Numbers]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)  DROP TABLE dbo.Numbers--===== Create and populate the Tally table on the fly SELECT TOP 1000000     IDENTITY(int,1,1) AS number  INTO dbo.Numbers  FROM master.dbo.syscolumns sc1,    master.dbo.syscolumns sc2--===== Add a Primary Key to maximize performance ALTER TABLE dbo.Numbers    ADD CONSTRAINT PK_numbers_number PRIMARY KEY CLUSTERED (number)--===== Allow the general public to use it GRANT SELECT ON dbo.Numbers TO PUBLIC--以上数字表创建一次即可,不需要每次都重复创建DECLARE @source_string  nvarchar(4000),     @sub_string    nvarchar(1024),     @nth       intSET @source_string = 'abcabcvvvvabc'SET @sub_string = 'abc'SET @nth = 2 ;WITH T AS(      SELECT ROW_NUMBER() OVER(ORDER BY number) AS nth,    number AS [Position In String] FROM dbo.Numbers n  WHERE n.number <= LEN(@source_string)    AND CHARINDEX(@sub_string, @source_string, n.number)-number = 0  ----OR  --AND SUBSTRING(@source_string,number,LEN(@sub_string)) = @sub_string) SELECT * FROM T WHERE nth = @nth

4. 通过CROSS APPLY结合charindex,适用于N值较小的时候,因为CROSS APPLY的次数要随着N的变大而增加,语句也要做相应的修改

declare @T table(source_string nvarchar(4000))insert into @T values('abcabc'),('abcabcvvvvabc')declare @sub_string nvarchar(1024)set @sub_string = 'abc'select source_string,    p1.pos as no1,    p2.pos as no2,    p3.pos as no3from @Tcross apply (select (charindex(@sub_string, source_string))) as P1(Pos)cross apply (select (charindex(@sub_string, source_string, P1.Pos+1))) as P2(Pos)cross apply (select (charindex(@sub_string, source_string, P2.Pos+1))) as P3(Pos)

5. 在SSIS里有内置的函数,但T-SQL中并没有

--FINDSTRING in SQL Server 2005 SSISFINDSTRING([yourColumn], "|", 2),--TOKEN in SQL Server 2012 SSISTOKEN(Col1,"|",3)

注:不难发现,这些方法和字符串拆分的逻辑是类似的,只不过一个是定位,一个是截取,如果要获取第N个字符左右的一个/多个字符,有了N的位置,再结合substring去截取即可;

三. 多个相同字符连续,合并为一个字符

最常见的就是把多个连续的空格合并为一个空格,解决思路有两个:

1. 比较容易想到的就是用多个replace

但是究竟需要replace多少次并不确定,所以还得循环多次才行

--把两个连续空格替换成一个空格,然后循环,直到charindex检查不到两个连续空格declare @str varchar(100)set @str='abc    abc   kljlk   kljkl'while(charindex(' ',@str)>0)begin  select @str=replace(@str,' ',' ')endselect @str

2. 按照空格把字符串拆开

对每一段拆分开的字符串trim或者replace后,再用一个空格连接,有点繁琐,没写代码示例,如何拆分字符串可参考:“第N次出现的位置”;

四. 是否为有效IP/身份证号/手机号等

类似IP/身份证号/手机号等这些字符串,往往都有自身特定的规律,通过substring去逐位或逐段判断是可以的,但SQL语句的方式往往性能不佳,建议尝试正则函数,见下。

五. 正则表达式函数

1. Oracle

从10g开始,可以在查询中使用正则表达式,它通过一些支持正则表达式的函数来实现:

Oracle 10 gREGEXP_LIKEREGEXP_REPLACEREGEXP_INSTRREGEXP_SUBSTROracle 11g (新增)REGEXP_COUNT

Oracle用REGEXP函数处理上面几个问题:

(1) 同一个字符/字符串,出现了多少次

select length(regexp_replace('123-345-566', '[^-]', '')) from dual;select REGEXP_COUNT('123-345-566', '-') from dual; --Oracle 11g 

(2) 同一个字符/字符串,第N次出现的位置

不需要正则,ORACLE的instr可以直接查找位置:

instr('source_string','sub_string' [,n][,m])

n表示从第n个字符开始搜索,缺省值为1,m表示第m次出现,缺省值为1。

select instr('abcdefghijkabc','abc', 1, 2) position from dual; 

(3) 多个相同字符连续,合并为一个字符

select regexp_replace(trim('agc f  f '),'\s+',' ') from dual; 

(4) 是否为有效IP/身份证号/手机号等

--是否为有效IPWITH IPAS(SELECT '10.20.30.40' ip_address FROM dual UNION ALLSELECT 'a.b.c.d' ip_address FROM dual UNION ALLSELECT '256.123.0.254' ip_address FROM dual UNION ALLSELECT '255.255.255.255' ip_address FROM dual)SELECT *FROM IPWHERE REGEXP_LIKE(ip_address, '^(([0-9]{1}|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]{1}|[0-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$');--是否为有效身份证/手机号,暂未举例

2. SQL Server

目前最新版本为SQL Server 2017,还没有对REGEXP函数的支持,需要通用CLR来扩展,如下为CLR实现REG_REPLACE:

--1. 开启 CLR EXEC sp_configure 'show advanced options' , '1'GORECONFIGUREGOEXEC sp_configure 'clr enabled' , '1'GORECONFIGUREGOEXEC sp_configure 'show advanced options' , '0';GO

 2. 创建 Assembly

--3. 创建 CLR 函数CREATE FUNCTION [dbo].[regex_replace](@input [nvarchar](4000), @pattern [nvarchar](4000), @replacement [nvarchar](4000))RETURNS [nvarchar](4000) WITH EXECUTE AS CALLER, RETURNS NULL ON NULL INPUTAS EXTERNAL NAME [RegexUtility].[RegexUtility].[RegexReplaceDefault]GO--4. 使用regex_replace替换多个空格为一个空格select dbo.regex_replace('agc f  f ','\s+',' ');

注:通过CLR实现更多REGEXP函数,如果有高级语言开发能力,可以自行开发;或者直接使用一些开源贡献也行,比如:http://devnambi.com/2016/sql-server-regex/

小结:

1. 非正则SQL语句的思路,对不同数据库往往都适用;

2. 正则表达式中的规则(pattern) 在不同开发语言里,有很多语法是相通的,通常是遵守perl或者linux shell中的sed等工具的规则;

3. 从性能上来看,通用SQL判断 > REGEXP函数 > 自定义SQL函数。

总结

以上所述是小编给大家介绍的SqlServer类似正则表达式的字符处理问题,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对站的支持!


  • 上一条:
    详解SQL Server表和索引存储结构
    下一条:
    SQLserver排序规则基本概念探索
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 分库分表的目的、优缺点及具体实现方式介绍(0个评论)
    • DevDB - 在 VS 代码中直接访问数据库(0个评论)
    • 在ubuntu系统中实现mysql数据存储目录迁移流程步骤(0个评论)
    • 在mysql中使用存储过程批量新增测试数据流程步骤(0个评论)
    • php+mysql数据库批量根据条件快速更新、连表更新sql实现(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-06
    • 2017-08
    • 2017-09
    • 2017-10
    • 2017-11
    • 2018-01
    • 2018-05
    • 2018-10
    • 2018-11
    • 2020-02
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-08
    • 2020-09
    • 2021-02
    • 2021-04
    • 2021-07
    • 2021-08
    • 2021-11
    • 2021-12
    • 2022-02
    • 2022-03
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-07
    • 2023-08
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-03
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客