2017-07-28 64 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; 
}