需求
当返回响应结构比较复杂,可以通过正则表达式来获取
实现
1.编写构造函数和成员变量
private String content;
public StringFixture() {
}
public StringFixture(String content) {
this.content = content;
}
2.实现方法(关键字)
public String getValueByRegGroup(String regular,int groupId){
String value = null;
value = RegularUtil.getStringByRegGroup(regular, this.content,groupId);
return value;
}
public static String getStringByRegGroup(String regular, String dircetContent,int groupId) {
String result = null;
Pattern pattern = Pattern.compile(regular);
Matcher matcher = pattern.matcher(dircetContent);
if (matcher.find()) {
result = matcher.group(groupId);
}
return result;
}
使用
1.引入类对应package
|import |
|own.slim.string|
2.编写脚本
|script |string fixture |!-[{"sn":1,"date":"20200708","pay":"78.98"},{"date":"20200709","pay":"90.77","sn":2}]-!|
|$pay_1= |getValueByRegGroup;|"sn":1.*?"pay":"(.{5})" |1 |
|$date_1=|getValueByRegGroup;|"sn":1.*?"date":"(.{8})" |1 |
|$pay_2= |getValueByRegGroup;|.*"pay":"(.{5})".*?"sn":2 |1 |
|$date_2=|getValueByRegGroup;|.*"date":"(.{8})".*?"sn":2 |1 |
3.测试
![getValueByKeyFromJsonString](https://img2020.cnblogs.com/blog/950020/202008/950020-20200810101826972-570454127.png)
总结
使用正则表达式获取值,难度是编写一个合适的表达式,如果可以熟练编写正则表达式,那么这种取值方式将是最灵活的方式。