「name:lala、id:1234、phone:123」のような文字列がありますが、たとえば、ID(数字)のみを取得したい-1234
これを行うための最良の方法は何ですか?
そのためのキャプチャグループで正規表現を使用できます。
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#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
他のソリューションよりも少し一般的です:
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));
}
}