SQL Server 2012:提取正则表达式组

 HoerenRegen 发布于 2022-12-18 20:22

我的数据库中有Markdown格式的文本.我想提取链接并计算我拥有的匹配链接的数量.我可以使用类似于此的查询获取包含链接的文本块列表:

SELECT post_text
FROM posts p
WHERE p.body like '%\[%](http%)%' ESCAPE '\'

我如何进入下一步,只提取文本的链接部分(括号中的部分)?如果我能得到这个,我可以计算这个特定链接在我的数据集中的次数.

一些样本数据:

"Visit [Google](http://google.com)"    -> Should return "http://google.com"
"Get an [iPhone](http://www.apple.com) (I like it better than Android)"   -> Should return "http://www.apple.com"
"[Example](http://example.com)"    -> Should return "http://example.com"
"This is a message"    -> Nothing to return on this one, no link
"I like cookies (chocolate chip)"  -> Nothing to return on this one, no link
"[Frank] says 'Hello'" -> Nothing to return on this one, no link

我正在使用SQL Server 2012(如果这方面的版本之间存在差异).

1 个回答
  • 假设实际数据并不比所述示例复杂,这应该可以在不诉诸RegEx的情况下工作:

    DECLARE @posts TABLE
    (
       post_id INT NOT NULL IDENTITY(1, 1),
       post_text NVARCHAR(4000) NOT NULL,
       body NVARCHAR(2048) NULL
    );
    INSERT INTO @posts (post_text, body) VALUES (N'first',
                                               N'Visit [Google](http://google.com)');
    INSERT INTO @posts (post_text, body) VALUES (N'second',
                                               N'Get an [iPhone](http://www.apple.com)');
    INSERT INTO @posts (post_text, body) VALUES (N'third',
                                               N'[Example](http://example.com)');
    INSERT INTO @posts (post_text, body) VALUES (N'fourth',
                                               N'This is a message');
    INSERT INTO @posts (post_text, body) VALUES (N'fifth',
                                               N'I like cookies (chocolate chip)');
    INSERT INTO @posts (post_text, body) VALUES (N'sixth',
                                               N'[Frankie] says ''Relax''');
    INSERT INTO @posts (post_text, body) VALUES (N'seventh',
                                               NULL);
    
    
    SELECT p.post_text,
           SUBSTRING(
                      p.body,
                      CHARINDEX(N'](', p.body) + 2,
                      CHARINDEX(N')', p.body) - (CHARINDEX(N'](', p.body) + 2)
                    ) AS [URL]
    FROM   @posts p
    WHERE  p.body like '%\[%](http%)%' ESCAPE '\';
    

    输出:

    post_text  URL
    first      http://google.com
    second     http://www.apple.com
    third      http://example.com
    

    PS:
    如果你真的想使用正则表达式,它们只能通过SQLCLR完成.您可以自己编写或下载预先完成的库.我写了一个这样的库,SQL#,它有一个包含RegEx函数的免费版本.但是只有在找不到T-SQL解决方案时才能使用这些解决方案,而目前情况并非如此.

    2022-12-18 20:29 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有