java正则从字符串中提取子字符串

package interface_response;




import java.util.ArrayList;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ParseLog {
public static void main(String[] args) {
/*
原始log为:{{"itemId":"9713"},{"opi"},{"itemId":"7813"},{"esc"},{"itemId":"713"},{"jse"},{"itemId":"413"},{"dollor"},{"itemId":"313"}}
原始log需要转义,可直接输入到https://www.bejson.com/jsonviewernew/,删除空格和转义,然后创建字符串对象
*/
String s = "{{\"itemId\":\"9713\"},{\"opi\"},{\"itemId\":\"7813\"},{\"esc\"},{\"itemId\":\"713\"},{\"jse\"},{\"itemId\":\"413\"},{\"dollor\"},{\"itemId\":\"313\"}}";
parse(s);
}

public static void parse(String s){
//正则示例:\"itemId\":\"8590\"
Pattern p=Pattern.compile("\"itemId\":\"\\d{3,5}\"");
Matcher m=p.matcher(s);
//确定正则匹配的个数,为新建数组的长度
String[] arr = new String[5];
int i = 0;

while(m.find()){  
//System.out.println(m.group());
if(i < 5){
//正则匹配的字符串赋值给数组元素
arr[i] = m.group();
}
i++;
}

//int tj = 0;
for(String j: arr){
//过滤最终所需字符串之外的冗余字符串
System.out.println(j.replace("\"itemId\":", "").replace("\"", ""));
//tj++;
}
//System.out.println(tj);
}

}

你可能感兴趣的:(java,正则,Programing,language-java)