2011-08-23 52 views
1

我正在使用以下代码来获取字符串中存在的整数。但是这会首次出现整数。只需打印14.我需要获取所有整数。有什么建议么。如何获取字符串中存在的所有整数?

Pattern intsOnly = Pattern.compile("\\d+"); 
      Matcher makeMatch = intsOnly.matcher("hello14 hai22. I am here 4522"); 
      makeMatch.find(); 
      String inputInt = makeMatch.group(); 

回答

2
Pattern intsOnly = Pattern.compile("\\d+"); 
Matcher makeMatch = intsOnly.matcher("hello14 hai22. I am here 4522"); 
String inputInt = null; 
while(makeMatch.find()) { 
    inputInt = makeMatch.group(); 
    System.out.println(inputInt); 
} 
+0

这不会打印第一个匹配项。请使用'do..while'来代替。 –

+0

它会的。如果没有匹配,使用'do ... while'会引发异常。 –

+0

@ Harry Joy它工作正常。 – Manikandan

4

提示:不要你需要循环得到所有的数字?

+1

+1不仅仅是在OP上抛出代码。 – mre

+0

@mre你说得对。我一直忘记作业问题。 –

1
List<Integer> allIntegers = new ArrayList<Integer>(); 
while(matcher.find()){ 
    allIntegers.add(Integer.valueOf(matcher.group)); 
} 
1

this nice tutorial on Regular Expressions in Java

要找到目标字符串的正则表达式的第一场比赛,调用myMatcher.find()。要查找下一个匹配项,请再次调用myMatcher.find()。当myMatcher.find()返回false时,表示没有进一步匹配,下次调用myMatcher.find()将再次找到第一个匹配项。当find()失败时,匹配器会自动重置为字符串的开头。

I.e.您可以使用以下代码:

while (makeMatch.find()) { 
    String inputInt = makeMatch.group(); 
    // do something with inputInt 
} 
+0

或者参阅“官方”Java教程[正则表达式](http://download.oracle.com/javase/tutorial/essential/regex/index.html)教程。 – mre

相关问题