すべてのテキストで","
との間の数字を見つける必要があります。
私は使いたくないし、でやりたい。
次のようなものですべての一致を簡単に取得できます。","
.split()
regexp
Pattern.compile(",?(\\d+),")
問題は、2 番目 (または 3 番目、または 4 番目) の一致しか取得できないかどうかです。
すべてのテキストを解析する必要はありません。N 件の一致後に停止したいと思います。
出来ますか?
5 番目の一致を取得する方法の例を次に示します。
String input = "11,22,33,44,55,66,77,88,99";
Pattern pattern = Pattern.compile(",?(\\d+),");
Matcher matcher = pattern.matcher(input);
int counter = 0;
int wantedMatch = 5;
while (matcher.find()) {
counter++;
if (counter == wantedMatch) {
String digits = matcher.group(1);
System.out.println(digits); // prints 55
break; // stop searching after n matches.
}
}
if (counter < wantedMatch) {
System.out.println("You wanted match #" + wantedMatch + ", there only were " + counter);
}
ニーズに合わせて調整する
public class Main {
public static void main(String[] args) {
String message = "123,456,789,101112,131415";
Pattern pattern = Pattern.compile(",?(\\d+),");
Matcher matcher = pattern.matcher(message);
int i = 1;
while (matcher.find()) {
//Finding the second match here
if (i == 2) {
System.out.println(matcher.group(1));
break;
}
i++;
}
}
}