如何使用正则表达式提取 SQL 中的字符串?
How to use regex to extract string in SQL?
文档说:
regexp_extract(string, pattern)
→ varchar
Returns字符串中正则表达式模式匹配的第一个子串
https://prestodb.io/docs/current/functions/regexp.html
我有以下查询
select regexp_extract('sssshttps://jira.domain.com/browse/PR-6835hhhh',
'/(https.*\/browse\/)(\w+\-\d+)/g')
这个returnnull
应该returnhttps://jira.domain.com/browse/PR-6835
正则表达式似乎可以在我检查过的许多正则表达式工具中使用。
为什么我无法提取 url link?
的子字符串
请注意,正斜杠和破折号不是正则表达式元字符,因此不需要转义,至少在 Presto 正则表达式中不需要。考虑这个版本:
select regexp_extract('sssshttps://jira.domain.com/browse/PR-6835hhhh',
'https.*?/browse/\w+-\d+')
这应该return:
https://jira.domain.com/browse/PR-6835
您当前的正则表达式似乎来自其他语言,例如 JavaScript 或 PHP,其中正则表达式文字具有分隔符 /
,因此需要 /
需要转义。
我刚刚编辑了我的答案,以便在匹配 https
和第一个 /browse
之间的内容时使用惰性圆点 .*?
。这应该可以解决您评论中提到的边缘情况,其中 .*
与多个 URL 匹配。
文档说:
regexp_extract(string, pattern)
→ varchar
Returns字符串中正则表达式模式匹配的第一个子串
https://prestodb.io/docs/current/functions/regexp.html
我有以下查询
select regexp_extract('sssshttps://jira.domain.com/browse/PR-6835hhhh',
'/(https.*\/browse\/)(\w+\-\d+)/g')
这个returnnull
应该returnhttps://jira.domain.com/browse/PR-6835
正则表达式似乎可以在我检查过的许多正则表达式工具中使用。
为什么我无法提取 url link?
请注意,正斜杠和破折号不是正则表达式元字符,因此不需要转义,至少在 Presto 正则表达式中不需要。考虑这个版本:
select regexp_extract('sssshttps://jira.domain.com/browse/PR-6835hhhh',
'https.*?/browse/\w+-\d+')
这应该return:
https://jira.domain.com/browse/PR-6835
您当前的正则表达式似乎来自其他语言,例如 JavaScript 或 PHP,其中正则表达式文字具有分隔符 /
,因此需要 /
需要转义。
我刚刚编辑了我的答案,以便在匹配 https
和第一个 /browse
之间的内容时使用惰性圆点 .*?
。这应该可以解决您评论中提到的边缘情况,其中 .*
与多个 URL 匹配。