判断输入的字符串是否为数字 发表于 2017-09-21 | | 阅读次数: 传入的str1包含中文、负数,位数很长的数字的字符串也能正常匹配12345678910111213141516171819202122232425262728293031import 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! Donate WeChat Pay Alipay