Python API测试请求URL的预验证列表
我想使用Python正则表达式预先验证下面的API测试请求URL列表 以下URL/请求字符串“R”列表包含两部分:Python API测试请求URL的预验证列表,python,regex,python-3.x,api,Python,Regex,Python 3.x,Api,我想使用Python正则表达式预先验证下面的API测试请求URL列表 以下URL/请求字符串“R”列表包含两部分: 请求和 此请求的有效性 除了前19个和最后3个(22-24),正则表达式代码工作正常,但不适用于请求20-21(参见列表def中的注释) 我确信有更有效的方法进行比赛,但他们给了我类似的结果。所以我只是简单的举个例子 import re R = [ # these are invalid and fail regex match "http://127.0.0.1:5000/x,b
import re
R = [
# these are invalid and fail regex match
"http://127.0.0.1:5000/x,bad",
"http://127.0.0.1:5000/countries?,bad",
"http://127.0.0.1:5000/countries?x,bad",
"http://127.0.0.1:5000/countries?=,bad",
"http://127.0.0.1:5000/countries?x=,bad",
"http://127.0.0.1:5000/countries&,bad",
"http://127.0.0.1:5000/countries&x,bad",
"http://127.0.0.1:5000/countries&=,bad",
"http://127.0.0.1:5000/countries&x=,bad",
"http://127.0.0.1:5000/countries&x=x,bad",
"http://127.0.0.1:5000/countries?code=AU?,bad",
"http://127.0.0.1:5000/countries?name=Australia?x,bad",
"http://127.0.0.1:5000/countries?name=Australia?=,bad",
"http://127.0.0.1:5000/countries?name=Australia?x=,bad",
"http://127.0.0.1:5000/countries?name=Australia?x=x,bad",
"http://127.0.0.1:5000/countries?name=Australia&,bad",
"http://127.0.0.1:5000/countries?name=Australia&x,bad",
"http://127.0.0.1:5000/countries?name=Australia&=,bad",
"http://127.0.0.1:5000/countries?name=Australia&x=,bad",
# these are valid requests and fail regex match
"http://127.0.0.1:5000/countries,good", # 20
"http://127.0.0.1:5000/countries?name=Australia,good", # 21
# these are valid and pass regex match
"http://127.0.0.1:5000/countries?code=AU&name=Australia,good", # 22
"http://127.0.0.1:5000/countries?name=New Zealand&calling_code=64,good", # 23
"http://127.0.0.1:5000/countries?code=AU&name=Australia&capital=Canberra,good", #24
]
for r in R:
divs.split(",")
m = re.match(r'http://127.0.0.1:5000/countries[\?[\s\w]{1,}=[\s\w]{1,}[\&[\s\w]{1,}=[\s\w]{1,}]{0,}]{0,1}', divs[0])
res = "good" if m != None else "bad"
print(divs[0] + " should be " + divs[1] + " and is " + res)
使用以下正则表达式:
^http://127\.0\.0\.1:5000/国家(?:?\w+=[\s\w]+(?:&\w+=[\s\w]+)*)?$/gm
请注意:
国家/地区之后的完整内容是可选的
需要转义,因为它在正则表达式世界中有特殊意义\w
匹配,右侧通过\s\w
组合匹配太棒了。。。非常感谢!