我需要在所有文字中找到","
和","
之间的数字
我不想使用.split()
并希望使用regexp
来执行此操作
我很容易就能得到类似的东西:
Pattern.compile(",?(\\d+),")
问题是,我可以只获得第二(或第三或第四)匹配吗? 我不需要解析所有文本,我想在N次匹配后停止 有可能吗?
答案 0 :(得分:4)
以下是如何获得第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);
}
根据您的需要进行调整
答案 1 :(得分:0)
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++;
}
}
}