I have a String like : "name:lala,id:1234,phone:123" but for example I want to get only the id (the numbers) - 1234
What is the best way to do this?
I have a String like : "name:lala,id:1234,phone:123" but for example I want to get only the id (the numbers) - 1234
What is the best way to do this?
You can avoid regex and use String#split method like this:
String str = "name:lala,id:1234,phone:123";
String id = str.split(",")[1].split(":")[1]; // sets "1234" to variable id
OR using some regex with String#replaceAll:
String id = str.replaceAll("^.*?,id:(\\d+),.*$", "$1"); // sets "1234" to variable id
A bit more generic than the other solutions:
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));
}
}