我有一个Java字符串对象。我只需要从中提取数字。我举个例子:
123456-789我要123456789
是否存在只提取数字的库函数?
谢谢你的回答。在我尝试这些之前,我需要知道我是否必须安装任何额外的llibraries?
我有一个Java字符串对象。我只需要从中提取数字。我举个例子:
123456-789我要123456789
是否存在只提取数字的库函数?
谢谢你的回答。在我尝试这些之前,我需要知道我是否必须安装任何额外的llibraries?
当前回答
您可以使用正则表达式和删除非数字。
str = str.replaceAll("\\D+","");
其他回答
代码:
public class saasa {
public static void main(String[] args) {
// TODO Auto-generated method stub
String t="123-456-789";
t=t.replaceAll("-", "");
System.out.println(t);
}
public class FindDigitFromString
{
public static void main(String[] args)
{
String s=" Hi How Are You 11 ";
String s1=s.replaceAll("[^0-9]+", "");
//*replacing all the value of string except digit by using "[^0-9]+" regex.*
System.out.println(s1);
}
}
输出:11
您可以使用正则表达式和删除非数字。
str = str.replaceAll("\\D+","");
使用正则表达式来匹配您的需求。
String num,num1,num2;
String str = "123-456-789";
String regex ="(\\d+)";
Matcher matcher = Pattern.compile( regex ).matcher( str);
while (matcher.find( ))
{
num = matcher.group();
System.out.print(num);
}
import java.util.*;
public class FindDigits{
public static void main(String []args){
FindDigits h=new FindDigits();
h.checkStringIsNumerical();
}
void checkStringIsNumerical(){
String h="hello 123 for the rest of the 98475wt355";
for(int i=0;i<h.length();i++) {
if(h.charAt(i)!=' '){
System.out.println("Is this '"+h.charAt(i)+"' is a digit?:"+Character.isDigit(h.charAt(i)));
}
}
}
void checkStringIsNumerical2(){
String h="hello 123 for 2the rest of the 98475wt355";
for(int i=0;i<h.length();i++) {
char chr=h.charAt(i);
if(chr!=' '){
if(Character.isDigit(chr)){
System.out.print(chr) ;
}
}
}
}
}