【问题标题】:Regexp Substring From URL来自 URL 的正则表达式子字符串
【发布时间】:2020-05-06 10:05:20
【问题描述】:

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

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

返回我想要的:

search/iphone_5s

但我被卡住了,并不真正了解如何使用 regexp_substr 来获取该数据。

我正在尝试使用此查询

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

只返回“搜索”字,当我尝试时

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

事实证明,直到最后一个 '&' 为止我都听懂了

【问题讨论】:

    标签: regex oracle oracle11g substring


    【解决方案1】:

    您可以使用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')
    

    请参阅regex demoonline Oracle demo

    模式详情

    • .* - 除换行符以外的任何零个或多个字符尽可能多
    • //google\.com/ - //google.com/ 子字符串
    • ([^/]+/) - 捕获组 1:除 / 之外的一个或多个字符,然后是 /
    • .* - 除换行符以外的任何零个或多个字符尽可能多
    • [?&]term= - ?&term= 子字符串
    • ([^&]+) - 捕获组 2:除 & 之外的一个或多个字符
    • .* - 除换行符之外的任何零个或多个字符尽可能多

    注意:要使用此方法并在未找到匹配项时获得空结果,请在正则表达式模式的末尾附加 |.+

    【讨论】:

    • 是否存在捕获诸如 https://example.com/?redirect_to=https://google.com/search/?term=iphone_5s 之类的 URL 的风险?由于 URL 的编码方式,我 100% 确定。
    • 谢谢,它有效。但是如果网址变成 google.co.uk 怎么办?
    • @BenoîtZu 当然这个字符串会被匹配,但是如果对输入字符串有明确的要求,这很容易解决。 Here 是当前方法的一种变体。
    • @DedeSoetopo 将com 替换为[^/]+,参见this demo
    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多