我有一个类似的字符串:“name:lala,id:1234,phone:123” 但例如我只想获取 id(数字) - 1234
做这个的最好方式是什么?
您可以避免使用正则表达式并使用 String#split 方法,如下所示:
String str = "name:lala,id:1234,phone:123";
String id = str.split(",")[1].split(":")[1]; // sets "1234" to variable id
或者使用一些带有 String#replaceAll 的正则表达式:
String id = str.replaceAll("^.*?,id:(\\d+),.*$", "$1"); // sets "1234" to variable id
您可以为此使用带有捕获组的正则表达式:
Pattern p = Pattern.compile("id:(\\d+)");
Matcher m = p.matcher("name:lala,id:1234,phone:123");
if (m.find()) {
System.out.println(m.group(1).toString());
}
比其他解决方案更通用一点:
String foo = "name:lala,id:1234,phone:123";
// get all all key/value pairs into an array
String[] array = foo.split(",");
// check every key/value pair if it starts with "id"
// this will get the id even if it is at another position in the string "foo"
for (String i: array) {
if (i.startsWith("id:")) {
System.out.println(i.substring(3));
}
}