Python字符串没有控制字符

时间:2016-10-04 20:28:35

标签: python string control-characters

我有代理字符串:

proxy = '127.0.0.1:8080'

我需要检查它是真正的字符串:

def is_proxy(proxy):
    return not any(c.isalpha() for c in proxy)

跳过字符串:

fail_proxy = 'This is proxy: 127.0.0.1:8080'

但有一段时间我喜欢:

fail_proxy2 = '127.0.0.1:8080\r'
is_proxy(fail_proxy2) is True
True

需要错误

1 个答案:

答案 0 :(得分:0)

使用re模块(regexp)尝试以下特定方法:

import re

def is_proxy(proxy):
    return re.fullmatch('^\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}:\d{1,5}$', proxy) is not None

proxy1 = '127.0.0.1:8080'
proxy2 = '127.0.0.1:8080\r'

print(is_proxy(proxy1))   # True
print(is_proxy(proxy2))   # False

关于端口号(\d{1,5}):范围 1-65535 可用于端口号