0

「name:lala、id:1234、phone:123」のような文字列がありますが、たとえば、ID(数字)のみを取得したい-1234

これを行うための最良の方法は何ですか?

4

3 に答える 3

3

そのためのキャプチャグループで正規表現を使用できます。

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());
}
于 2012-05-16T21:47:53.987 に答える
3

正規表現を回避し、次のような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
于 2012-05-16T21:49:03.640 に答える
1

他のソリューションよりも少し一般的です:

    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));
        }
    }
于 2012-05-16T21:56:24.093 に答える