首页 > 解决方案 > 如何匹配 URL 但不是模式

问题描述

我需要 js 正则表达式来提取字符串中的 url,但不需要像这样的模式:[[url=http://example.com/foo]].

示例:这是一个测试字符串http://google.com, https://www.youtube.com/watch?v=K_m7NEDMrV0, https://instagram.com/hellow/ ftp://google.com [[url=https://instagram.com/hellow/]]

正则表达式应该提取: http://google.com https://www.youtube.com/watch?v=K_m7NEDMrV0&test=1 https://instagram.com/hellow/

标签: javascriptregexurl

解决方案


我不确定你的意思,这是适合你的解决方案吗?

import re

# input strings
url_strings = ['http://google.com',
               'https://www.youtube.com/watch?v=K_m7NEDMrV0',
               'https://instagram.com/hellow/',
               'ftp://google.com [[url=https://instagram.com/hellow/]]']

for i in range(len(url_strings)):
    r1 = re.findall(r'\[', str(url_strings[i]))
    if not r1:
        print(url_strings[i])

推荐阅读