Fork me on GitHub

判断输入的字符串是否为数字

传入的str1包含中文、负数,位数很长的数字的字符串也能正常匹配

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
30
31
import java.math.BigDecimal;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class jisuanqiceshi {
public static void main(String[] args) {
Scanner str1= new Scanner(System.in);
System.out.println("请输入您要判断的字符串: ");
String str2 = str1.next();
System.out.println(isNumeric(str2));
str1.close();
}
//用正则表达式判断字符串是否为数字(含负数)
public static boolean isNumeric(String str) {
String regEx = "-?[0-9]+\\.?[0-9]*";
Pattern pat = Pattern.compile(regEx);
try{
regEx= new BigDecimal(str).toString();
} catch (Exception e){
return false;//异常 说明包含非数字
}
Matcher mat = pat.matcher(str);
if (mat.find()) {
return true;
}
else {
return false;
}
}
}

多组输入试过,没成功,希望大家多多指教!

Your support will encourage me to continue to create!