从URL中提取子字符串的正则表达式

3

我需要从URL中检索一些单词:

WebViewActivity - https://google.com/search/?term=iphone_5s&utm_source=google&utm_campaign=search_bar&utm_content=search_submit

return I want :

search/iphone_5s

但我卡住了,不太明白如何使用regexp_substr来获取那个数据。

我正在尝试使用这个查询:

regexp_substr(web_url, '\google.com/([^}]+)\/', 1,1,null,1)

仅返回“search”单词,并且当我尝试时

regexp_substr(web_url, '\google.com/([^}]+)\&', 1,1,null,1)

原来我获取的所有单词都是直到最后一个'&'为止。
1个回答

3
您可以使用 REGEXP_REPLACE 正则表达式进行匹配整个字符串但捕获两个子字符串并替换为两个反向引用以捕获组值:
REGEXP_REPLACE(
    'WebViewActivity - https://google.com/search/?term=iphone_5s&utm_source=google&utm_campaign=search_bar&utm_content=search_submit',
    '.*//google\.com/([^/]+/).*[?&]term=([^&]+).*',
    '\1\2')

请查看正则表达式演示在线Oracle演示模式详情
  • .* - 匹配除换行符以外的任意零个或多个字符,尽可能多地匹配
  • //google\.com/ - 匹配//google.com/子字符串
  • ([^/]+/) - 捕获组1: 一个或多个非 / 字符,然后是一个 /
  • .* - 匹配除换行符以外的任意零个或多个字符,尽可能多地匹配
  • [?&]term= - ?& 和一个term=子字符串
  • ([^&]+) - 捕获组2: 一个或多个非 & 字符
  • .* - 匹配除换行符以外的任意零个或多个字符,尽可能多地匹配
注意: 若要使用此方法并在未找到匹配项时获取空结果,请在正则表达式模式末尾添加|.+

有没有可能捕获到像 https://example.com/?redirect_to=https://google.com/search/?term=iphone_5s 这样的URL?由于URL的编码方式,我不是100%确定。 - Benoît Zu
谢谢,它有效。但是如果网址变成google.co.uk怎么办? - Dede Soetopo
1
@BenoîtZu 确定这个字符串会被匹配,但如果输入字符串有明确的要求集,那么这很容易修复。这里是当前方法的一个变体。 - Wiktor Stribiżew
@DedeSoetopo 将 com 替换为 [^/]+,请参见此演示 - Wiktor Stribiżew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接