将下图中的字符进行拆分抓取解析
这块没有写实体类
实现类
public List<Policy> excute(String input){
// 这块为匹配的正则表达式
String pattern = "Rule Name\\s+Hit Count\\s+Timestamp\\n-+\\n[\\w\\s:]+\\n([\\w\\s.-]+)";
// 将给定的正则表达式编译为给定标志的模式,创建一个匹配器,改匹配器将根据此模式匹配给定的输入
Matcher matcher = Pattern.compile(pattern,Pattern.MULTILINE).matcher(input);
List<Policy> policyList = new ArrayList<>();
String content = "";
if (matcher.find()){
// 第一组
content = matcher.group(1);
// 以/n进行分割
String[] strings = content.split("\n");
// 第一个正则为第一列的第二个正则为紧挨着的空格以此类推
String p = "(\\S+)(\\s+)(\\S+)(\\s+)(\\S+)(\\s+)";
for (int i = 0; i < strings.length; i++){
Matcher ms = Pattern.compile(p).matcher(strings[i]);
while (ms.find()){
// 获取到Rule Name列
String name = ms.group(1);
// 获取到Hit Count列
String count = ms.group(3);
// 获取到Timestamp列
String timestamp = ms.group(5);
policyList.add(new Policy.Builder().setHitCount(Integer.parseInt(count)).setName(name).setTimeStamp(timestamp).build());
}
}
return policyList;
}
return null;
}
测试类
@Test
public void testRegex(){
String input = "这块写的是将下列字符串查询出来的命令\n" +
"\n" +
"Rule Name\t\t\t\t\tHit Count\t\t\t\t\tTimestamp\n" +
"--------------------------------------------------------------------------------\n" +
"Slot 1 DP 0:\n" +
"zone111\t\t\t\t\t0\t\t\t\t\t-\t\t\t\t\t\n" +
"any_2_trust\t\t\t\t\t0\t\t\t\t\t-\t\t\t\t\t\n" +
"l3_2_l3_93a4f\t\t\t\t\t0\t\t\t\t\t-\t\t\t\t\t\n" +
"intrazone-default\t\t\t\t\t0\t\t\t\t\t-\t\t\t\t\t\n" +
"interzone-default\t\t\t\t\t0\t\t\t\t\t-\t\t\t\t\t";
List<Policy> list = new PolicyMappingRegex().excute(input);
}