2012-10-07 21 views
1

在Java中,我使用模式和匹配器在一组字符串中查找所有“.A(一个数字)”实例以检索数字。Java正则表达式与句点部分匹配

我遇到了问题,因为文件中的一个单词是“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); 
    } 
} 

回答

1

短采样为您提供:

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