And*_*ndy 3 regex sql sql-server sql-server-2012
我的数据库中有Markdown格式的文本.我想提取链接并计算我拥有的匹配链接的数量.我可以使用类似于此的查询获取包含链接的文本块列表:
SELECT post_text
FROM posts p
WHERE p.body like '%\[%](http%)%' ESCAPE '\'
Run Code Online (Sandbox Code Playgroud)
我如何进入下一步,只提取文本的链接部分(括号中的部分)?如果我能得到这个,我可以计算这个特定链接在我的数据集中的次数.
一些样本数据:
"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
Run Code Online (Sandbox Code Playgroud)
我正在使用SQL Server 2012(如果这方面的版本之间存在差异).
假设实际数据并不比所述示例复杂,这应该可以在不诉诸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 '\';
Run Code Online (Sandbox Code Playgroud)
输出:
post_text URL
first http://google.com
second http://www.apple.com
third http://example.com
Run Code Online (Sandbox Code Playgroud)
PS:
如果你真的想使用正则表达式,它们只能通过SQLCLR完成.您可以自己编写或下载预先完成的库.我写了一个这样的库,SQL#,它有一个包含RegEx函数的免费版本.但是只有在找不到T-SQL解决方案时才能使用这些解决方案,而目前情况并非如此.
| 归档时间: |
|
| 查看次数: |
5325 次 |
| 最近记录: |