如何在 substring_index 中传递多个分隔符

How to pass multiple delimeters in substring_index

我想查询 https:// 或 http:// 及其后的第一个分隔符之间的字符串。例如,如果字段包含:

https://google.com/en/
https://www.yahoo.com?en/

我想得到:

google.com
www.yahoo.com

我将捕获 / 的初始查询仅包含两个 substring_index,如下所示:

SELECT substring_index(substring_index(mycol,'/',3),'://',-1)
FROM mytable;

现在我发现网址可能包含多个分隔符。我希望我的 statament 捕获多个分隔符的可能性(每个分隔符都是一个单独的字符):

:/?#[]@!$&'()*+,;=

如何在我的声明中做到这一点?我尝试了 this solution 但最终结果是由于语法错误无法执行命令,而我确定我遵循了解决方案。谁能帮助我正确构建查询以捕获上面列出的所有定界字符?

我在 Ubuntu 18.04 上使用 MySQL workbecnh 6.3。

编辑:

第一个 URL 示例中的一些更正。

在 MySQL 8+ 中,这应该有效:

SELECT regexp_replace(regexp_substr(mycol, '://[a-zA-Z0-9_.]+[/:?]'), '[^a-zA-Z0-9_.]', '')
FROM (SELECT 'https://google.com/en' as mycol union all
      SELECT 'https://www.yahoo.com?en'
     ) x

在旧版本中,这更具挑战性,因为无法搜索字符串 class。

一种暴力破解方法是:

select (case when substring_index(mycol, '://', -1) like '%/%'
             then substring_index(substring_index(mycol, '://', -1), '/', 1)
             when substring_index(mycol, '://', -1) like '%?%'
             then substring_index(substring_index(mycol, '://', -1), '?', 1)
             . . .   -- and so on for each character
             else substring_index(mycol, '://', -1) 
        end) as what_you_want

[a-zA-Z0-9_.] 类似于您域名的有效字符 class。

首先,请注意 https://www.yahoo.com?en/ 似乎不太可能 URL,因为它在查询字符串中包含一个路径分隔符。无论如何,如果您使用的是 MySQL 8+,请考虑使用其正则表达式功能。 REGEXP_REPLACE 函数在这里很有用,使用以下模式:

https?://([A-Za-z_0-9.-]+).*

示例查询:

WITH yourTable AS (
    SELECT 'https://www.yahoo.com?en/' AS url UNION ALL
    SELECT 'no match'
)

SELECT
    REGEXP_REPLACE(url, 'https?://([A-Za-z_0-9.-]+).*', '') AS url
FROM yourTable
WHERE url REGEXP 'https?://[^/]+';

Demo

术语</code>指的是正则表达式模式中的第一个<em>capture</em>组。显式捕获组由括号中的数量表示。在这种情况下,这里是捕获组(下面突出显示):</p> <pre><code>https?://([A-Za-z_0-9.-]+).* ^^^^^^^^^^^^^^^

即捕获组是URL路径的第一部分,包括域、子域等