我有这个字符串:page: 4, response: 5, alt: 99
我想将值提取到数组中:
[4,5,99]
这是我的代码,有没有办法改进它?
pattern = "page: d+?,response: d+?, alt: d+?";
String first = origianlString.replaceAll(pattern, "$0");
String second = origianlString.replaceAll(pattern, "$1");
String third = origianlString.replaceAll(pattern, "$2");
答案 0 :(得分:2)
你可以试试这个:
String regex = "\\D+?(\\d+)\\D+?(\\d+)\\D+?(\\d+)";
String input = "page: 4, response: 5, alt: 99";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if (m.find()) {
String first = m.group(1);
String second = m.group(2);
String third = m.group(3);
System.out.println("[" + first + "," + second + "," + third+ "]");
}
<强>输出:强>
[4,5,99]
答案 1 :(得分:-1)
使用RepalceAll
String str = "page: 4, response: 5, alt: 99";
str = str.replaceAll("[^0-9]+", " ");
System.out.println(Arrays.asList(str.trim().split(" ")));
答案 2 :(得分:-1)
最好的办法是使用拆分方法,假设值总是用“,”分隔
例如:
String data = "page: 4, response: 5, alt: 99";
String[] split = data.split(","); //Get each individual entry
int[] values = new int[split.length]; //Create array to hold values
for (int i = 0; i < split.length; i++) { //Go through each value
String str = split[i]; //Get the string
str = str.trim(); //remove whitespace
String[] pair = str.split(":"); //Split to get key and value separate
values[i] = Integer.parseInt(pair[1]); //Put int value into array
}