Python正则表达式捕获各种url模式组

标签 python regex

我有包含这样字符串的数据集,我想从中删除所有 url

http://google.com 在这种情况下找不到正则表达式 https://google.com http//google com/测试一些乱码 https//google 。 com/test/test1 很棒的 http.//google.org

现在,我正在使用这个正则表达式模式来查找所有 url:

https?:?\s?\/\/\s?\S+

现在,理想情况下,它应该捕获所有 url,例如在这种情况下,

  • http://google.com

  • https://google.com

  • http//google com/test

  • https//谷歌。 com/test/test1

  • http.//google.org

但是使用我的正则表达式模式,它只捕获

  • http://google.com

  • https://google.com

  • http//google

  • https//google

链接到 Regex .

最佳答案

你可以使用

https?[:.]?\s?\/\/(?:\s*[^\/\s.]+)+(?:\s*\.\s*[^\/\s.]+)*(?:\s*\/\s*[^\/\s]+)*

参见 regex demo .

详情

  • https? - httphttps
  • [:.]? - 可选的 :.
  • \s? - 一个可选的空格 -\/\/ - // 字符序列
  • (?:\s*[^\/\s.]+)+ -(匹配所有域名部分,直到 TLD 之前的最后一个 .)1或多次出现
    • \s* - 0 个或多个空格
    • [^\/\s.]+ - 除了 /. 和空格之外的 1 个或多个字符
  • (?:\s*\.\s*[^\/\s.]+)* - 0 个或多个序列
    • \s*\.\s* - 用 0+ 个空格包围的点
    • [^\/\s.]+ - 除了 /. 和空格之外的 1 个或多个字符
  • (?:\s*\/\s*[^\/\s]+)* - 0 个或多个序列
    • \s*\/\s* - 包含 0+ 个空格的 /
    • [^\/\s]+ - 除了 / 和空格之外的 1 个或多个字符

关于Python正则表达式捕获各种url模式组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62307275/

相关文章:

javascript - 如何创建正则表达式来过滤掉有关长度、大小写和字符类别的复杂条件的结果

regex - 如何 grep 包含两次或多次列出特定字母的单词列表?

python - 从本地 PNG 创建 Django 文件引发 UnicodeDecodeError

python - 有没有办法使用 vlc python 模块播放加载到内存的视频

python - 将十六进制字符(连字)转换为utf-8字符

javascript - 正则表达式最大长度为 12,无特殊字符和其他条件

javascript - Jquery - Chrome 和 Firefox 中的正则表达式按键操作不同

javascript - 改进 JavaScript 正则表达式以匹配带有或不带有结束标记的标记内的内容,不包括 self

python - 去抖 celery 任务?

python - 使用 Bokeh 在 map 图 block 顶部添加分区统计图