0

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?

1
  • I know I can just search for the start index ( using substring or indexof) of Id and then get the int but I have a longer string with many data so I thought there is something better than this... Commented May 16, 2012 at 21:49

3 Answers 3

3

You can use regular expressions with a capturing group for that:

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());
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

1

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));
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.