【问题标题】:how to see if there is any ips in a string [duplicate]如何查看字符串中是否有任何ips [重复]
【发布时间】:2020-08-31 16:40:25
【问题描述】:

我有兴趣创建一个函数,如果字符串包含使用 python 的 IP 地址,它将返回 true。

def having_IP_Adress(URL):
    URL.match('^(http|https)://\d+\.\d+\.\d+\.\d+\.*')
print (having_IP_Adress("http://197.248.5.23/"))

但它给了我一个错误

【问题讨论】:

  • 请同时发布错误信息。在解释和指导您找到固定解决方案时会有所帮助????
  • 请从intro tour 重复on topichow to ask。我们希望您在此处发布之前研究该主题。有许多已发布的解决方案(取决于您需要的准确度)来检测有效 IP 地址。对于错误消息,我们需要预期的minimal, reproducible example

标签: python string ip


【解决方案1】:

您可以将re 模块用于正则表达式:

import re

def having_IP_Adress(URL):
    match = re.search(r'^(http|https)://\d+\.\d+\.\d+\.\d+', URL)
    if match is not None:
        return True
    else:
        return False

print(having_IP_Adress("http://197.248.5.23/"))

如果没有找到匹配项,则返回 None,因此您可以轻松地使用它来检查

【讨论】:

  • 您需要使用原始字符串 r'...' 作为正则表达式,或者将所有反斜杠加倍。但是最后一个反斜杠也是错误的。
  • @tripleee 谢谢,已编辑。还有其他建议吗?
  • 也许不要试图回答表达不清的问题;事实证明,OP 往往意味着其他东西,或者不理解您的答案,或者根本就不会回来。但是让我们看看。
【解决方案2】:

之前编译一次正则表达式甚至可以提高性能。

URL 的验证主要在 Stackoverflow 中介绍。以下 sn-p 的灵感来自 Django 的代码:

import re

def is_valid_ip(url):
   regex = re.compile(
    r'^https?://' # http:// or https://
    r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ip, not checked for valid ranges (0..255)!
    r'(?:/?|[/?]\S+)$', re.IGNORECASE)
    return url is not None and regex.search(url)

查看How do you validate a URL with a regular expression in Python?的答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-01
    • 2016-02-07
    • 2013-12-04
    • 1970-01-01
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    相关资源
    最近更新 更多