java從字串中提取數字的簡單例項
阿新 • • 發佈:2019-02-17
1 String類提供的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package
測試練習;
import
Java.util.*;
public
class get_StringNum {
/**
*2016.10.25
*/
public
static void main(String[] args) {
String str =
"love23next234csdn3423javaeye" ;
str=str.trim();
String str2= "" ;
if (str !=
null && ! "" .equals(str)){
for ( int
i= 0 ;i<str.length();i++){
if (str.charAt(i)>= 48
&& str.charAt(i)<= 57 ){
str2+=str.charAt(i);
}
}
}
System.out.println(str2);
}
}
output:
232343423
|
這個方法有個明顯的缺點,只能把數字全部提取到一起,不能分別提取。當然也可以改進,有興趣的朋友可以試試。
2 正則表示式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import
java.util.*;
import
java.util.regex.Matcher;
import
java.util.regex.Pattern;
public
class get_StringNum {
/**
*2016.10.25
*/
public
static void main(String[] args) {
String a= "love23next234csdn3423javaeye" ;
String regEx= "[^0-9]" ;
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(a);
System.out.println( m.replaceAll( "" ).trim());
}
}
output:
232343423
|
Pattern ,Matcher是java.util.regex軟體包裡的兩個類,具體用法大家可以查閱一下api。同樣也不能單個提取數字。