【问题标题】:Excluding a string containing character regex [duplicate]排除包含字符正则表达式的字符串[重复]
【发布时间】:2020-04-22 23:18:00
【问题描述】:

目前我正在尝试使用正则表达式从包含正确和不正确 URL 的字符串中获取正确的 URL。代码的结果应该给出输入字符串中正确 URL 的列表。问题是我无法摆脱"http://example{.com",因为我想出的只是获得"{" 字符并在结果中获得"http://example"

我正在检查的代码如下:

import re
text = "https://example{.com http://example.com http://example.hgg.com/da.php?=id42 http\\:example.com http//: example.com"
print(re.findall('http[s]?[://](?:[a-zA-Z0-9$-_@.&+])+', text))

那么有没有一种好方法可以获取所有匹配项,但不包括包含错误字符的匹配项(如"{")?

【问题讨论】:

  • 所有的网址都是用空格隔开的吗?
  • 是的。我需要从中提取 URL 的字符串是包含由空格分隔的各种版本的 URL 的字符串
  • 我需要从中提取 URL 的字符串是一个字符串,其中包含用空格分隔的各种版本的 URL 在这种情况下,您应该做的是拆分潜在的 URL,然后检查每一个,这意味着 这是重复的,正如@Bruno 所指出的那样 我要补充的唯一一点是,您真的不应该在其中的任何部分使用正则表达式。
  • 另一个可能有用的问题:stackoverflow.com/q/22238090/11301900.

标签: python regex


【解决方案1】:

很难确切地知道您需要什么,但这应该会有所帮助。用正则表达式解析 URL 很困难。但是 Python 带有一个 URL 解析器。看起来它们是空格分隔的,所以你可以做这样的事情

from urllib.parse import urlparse


text = "https://example{.com http://example.com http://example.hgg.com/da.php?=id42 http\\:example.com http//: example.com"

for token in text.split():
    result = urlparse(token)
    if result.scheme in {'http', 'https'} \
            and result.netloc \
            and all(c == '.' or c.isalpha() for c in result.netloc):
        print(token)

将文本拆分为字符串列表text.split,尝试解析每个项目urlparse(token)。如果方案是 http 或 https 并且域(a.k.a netloc)是非空的并且所有字符都是 a-z 或点,则打印。

【讨论】:

    【解决方案2】:

    在您的示例中,URL 以空格结尾,因此您可以使用先行查找下一个空格(或字符串的结尾)。为此,您可以使用:(?=\s|$)

    您的 RegEx 可以修复如下:

    print(re.findall(r'http[s]?[:/](?:[a-zA-Z0-9$-_@.&+])+(?=\r|$)', text))
    

    注意:不要忘记使用原始字符串(以“r”为前缀)。

    您还可以改进您的 RegEx,例如:

    import re
    
    text = "https://example{.com http://example.com http://example.hgg.com/da.php?=id42 http\\:example.com http//: example.com"
    
    URL_REGEX = r"(?:https://|http://|ftp://|file://|mailto:)[-\w+&@#/%=~_|?!:,.;]+[-\w+&@#/%=~_|](?=\s|$)"
    
    print(re.findall(URL_REGEX, text))
    

    你得到:

    ['http://example.com', 'http://example.hgg.com/da.php?=id42']
    

    要想有一个好的RegEx,你可以看看这个问题:“What is the best regular expression to check if a string is a valid URL?”

    这个 RegEx for Python 的答案点:

    URL_REGEX = re.compile(
        r'(?:http|ftp)s?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|'  # ...or ipv4
        r'\[?[A-F0-9]*:[A-F0-9:]+\]?)'  # ...or ipv6
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)', re.IGNORECASE)
    

    它就像一个魅力!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-27
      • 2020-08-25
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      • 2018-09-10
      相关资源
      最近更新 更多