0

我需要在所有文本","之间找到数字。 我不想使用并且想要使用. 我可以通过以下方式轻松获得所有匹配项:","
.split()regexp

Pattern.compile(",?(\\d+),")

问题是,我只能获得第二(或第三或第四)场比赛吗?
我不需要解析所有文本,我想在 N 个匹配后停止。
是否可以?

4

2 回答 2

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

使其适应您的需求

于 2013-01-24T10:54:20.320 回答
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++;
        }
    }
}
于 2013-01-24T10:52:42.987 回答