0

次のような文字列があるとします。

クラス:クラス shape_assignment.SquareX-座標:314Y-座標:50

そこから 2 つの数字 (つまり、314 と 50) を抽出するにはどうすればよいですか?

4

4 に答える 4

6

Use Regex:

String s = "Class:class shapes_assignment.SquareX-Coordinate:314Y-Coordinate:50";
  Pattern pat = Pattern.compile("(\\d)+");
  Matcher mat = pat.matcher(s);

  while(mat.find()){

   System.out.println(mat.group()); // You can store these numbers in variables
}

You can use the below code to Convert and Store the numbers:

ArrayList<Integer> numbers = new ArrayList<Integer>();

while(mat.find()){

    System.out.println(mat.group());

    numbers.add(Integer.parseInt(mat.group()));  
}
于 2012-11-16T17:23:34.580 に答える
1

使用できますMatcher.matches()

String str = "Class:class shapes_assignment.SquareX-Coordinate:314Y-Coordinate:50";
Matcher m = Pattern.compile(".*?(\\d+).*?(\\d+).*").matcher(str);
if (m.matches()) {
   System.out.println(m.group(1));
   System.out.println(m.group(2));
}

出力:

314
50
于 2012-11-16T17:27:56.830 に答える
0

Iterate over every character of the String. If the character matches 0 - 9 then add it to a new string foo. Stop adding characters to this string when a character is not a number in consecutive order.

Once this is done, convert the string foo to an integer.

I hope this helps.

于 2012-11-16T17:23:41.490 に答える
0

数字以外の文字で文字列を分割できます。

String s = "Class:class shapes_assignment.SquareX-Coordinate:314Y-Coordinate:50"; 
String[] numbers = s.split("[^\\d]+");

入力が数字以外の文字で始まる場合、最初の要素は空の文字列になることに注意してください。

次に、配列の空でない各文字列を で解析できますInteger.parseInt()

完全な作業コード:

public static void main(String[] args) {
    String s = "Class:class shapes_assignment.SquareX-Coordinate:314Y-Coordinate:50";
    String[] numbers = s.split("[^\\d]+");
    for (String number : numbers) {
        if (!number.isEmpty()) {
            int i = Integer.parseInt(number);
            System.out.println("i = " + i);
        }
    }
}
于 2012-11-16T17:25:54.323 に答える