我编写了一个程序来查找匹配项。它工作正常。如果字符串不正确,它必须返回 false。例如,如果我的 string_ 包含 2 个逗号,而不是 reject 或任何其他字符串,则它必须返回 false。我的字符串只期望字符串为 reject 或 any
import re
string_ = '''192.168.1.1,192.168.1.2/32,192.168.1.5-192.168.1.7,reject,any,
reject,192.168.1.1/32,reject,any,
172.168.1.4-172.168.1.4,reject'''
result = re.findall('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/?\d{0,}|[any|reject]+', string_)
#print(result)
if result :
print (True)
期望下面的字符串为 false
test = '''192.168.1.1,192.168.1.2/32,192.168.1.5-192.168.1.7,reject,any,ip_address
reject,192.168.1.1/32,reject,any,
172.168.1.4-172.168.1.4,reject'''
bool(re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/?\d{0,}|[any|reject]+', test))
预期结果为假,我的结果为真
test1 = '''192.168.1.1,192.168.1.2/32,192.168.1.5-192.168.1.7,reject,any,,,,
reject,192.168.1.1/32,reject,any,
172.168.1.4-172.168.1.4,reject'''
bool(re.search('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\/?\d{0,}|[any|reject]+', test1))
预期结果为假,我的结果为真
预期结果
错误
请您参考如下方法:
你可以使用
^(?:\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?(?:-\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?)?|reject|any)(?:\s*,\s*(?:\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?(?:-\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?)?|reject|any))*$
由于正则表达式由 block 组成,因此更容易在代码中动态构建它:
import re
string_ = '''192.168.1.1,192.168.1.2/32,192.168.1.5-192.168.1.7,reject,any,ip_address
reject,192.168.1.1/32,reject,any,
172.168.1.4-172.168.1.4,reject'''
ip_rx = r'\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?'
# More precise:
# ip_rx = r'(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}'
block=r"(?:{0}(?:-{0})?|reject|any)".format(ip_rx)
print(bool(re.search(r'^{0}(?:\s*,\s*{0})*$'.format(block), string_))) # => False
参见 Python demo
详情
^{0}(?:\s*,\s*{0})*$- 匹配完全匹配block模式的字符串出现 0 次或多次、和block模式(?:{0}(?:-{0})?|reject|any)是匹配ip< 的模式,可以选择后跟block模式-和ip模式或reject或any子字符串<\d{1,3}(?:\.\d{1,3}){3}(?:/\d+)?是ip可以改进以仅匹配有效 IP 的模式,(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9 ]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}。
