在 Java 中,我使用 Pattern 和 Matcher 来查找一组字符串中“.A(数字)”的所有实例,以检索数字。
我遇到了问题,因为文件中的单词之一是“P.A.M.X”。并且数字返回 0。它不会遍历文件的其余部分。我尝试过使用许多不同的正则表达式,但我无法克服“P.A.M.X.”的出现。并进入下一个“.A(数字)”
for (int i = 0; i < input.size(); i++) {
Pattern pattern = Pattern.compile("\\.A\\s\\d+");
Matcher matcher = pattern.matcher(input.get(i));
while (matcherDocId.find())
{
String matchFound = matcher.group().toString();
int numMatch = 0;
String[] tokens = matchFound.split(" ");
numMatch = Integer.parseInt(tokens[1]);
System.out.println("The number is: " + numMatch);
}
}
最佳答案
为您提供的简短示例:
Pattern pattern = Pattern.compile("\\.A\\s(\\d+)"); // grouping number
Matcher matcher = pattern.matcher(".A 1 .A 2 .A 3 .A 4 *text* .A5"); // full input string
while (matcher.find()) {
int n = Integer.valueOf(matcher.group(1)); // getting captured number - group #1
System.out.println(n);
}
关于Java正则表达式与句点部分匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12766205/