gpt4 book ai didi

Java 正则表达式。在长文本中仅查找一个匹配项

转载 作者:行者123 更新时间:2023-12-01 18:54:38 25 4
gpt4 key购买 nike

我需要在所有文本中查找 ",""," 之间的数字。
我不想使用 .split(),而是想使用 regexp 来实现。
我可以轻松地获得所有匹配的东西:

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

问题是,我只能得到第二个(或第三个、第四个)匹配吗?
我不需要解析所有文本,我想在 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);
}

根据您的需求进行调整

关于Java 正则表达式。在长文本中仅查找一个匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14499284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com