2017-07-28 69 views
1

所以我有一个字符串22test12344DC1name23234343dc提取物首次发现INT从字符串

我想提取找到的第一个完整的INT从字符串的最佳途径。

所以这将从上面的例子返回22和1。第一个完整的INT的发现

我试过这种方式,但我不想在第一个字符后的任何值。

mystr.split("[a-z]")[0] 
+0

考虑正则表达式中的字符串,而不是匹配的号码! –

+0

'我不想在第一个char之后有任何值。'你想如何获得22 then –

+1

22test12344DC 22是第一个int。 – Blawless

回答

2

试试这个。

String s = "22test12344DC"; 
String firstInt = s.replaceFirst(".*?(\\d+).*", "$1"); 
System.out.println(firstInt); 

结果:

22 
1

使用正则表达式和正确的模式将这样的伎俩: here is one example

Pattern.compile("\\d+|\\D+") 

然后打破while循环,因为你只需要第一次比赛

String myCodeString = "22test12344DC"; 
myCodeString = "1name23234343dc"; 
Matcher matcher = Pattern.compile("\\d+|\\D+").matcher(myCodeString); 

while (matcher.find()) { 
    System.out.println(matcher.group()); 
    break; 
}