java 字符串—数字常用处理

时间:2022-10-30 18:15:02
 // 判断一个字符串是否都为数字
public boolean isDigit(String strNum) {
return strNum.matches("[0-9]{1,}");
} // 判断一个字符串是否都为数字
public boolean isDigit(String strNum) {
Pattern pattern = Pattern.compile("[0-9]{1,}");
Matcher matcher = pattern.matcher((CharSequence) strNum);
return matcher.matches();
} //截取数字
public String getNumbers(String content) {
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
return matcher.group(0);
}
return "";
} // 截取非数字
public String splitNotNumber(String content) {
Pattern pattern = Pattern.compile("\\D+");
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
return matcher.group(0);
}
return "";
}

  含小数点

public static boolean isNum(String str){
return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
}

取连续数字

private static Set<Integer> getNumsFromStr(String str) {

  String[] ary = str.replaceAll("[^\\d]", " ").split("\\s+");

  Set<Integer> set = new TreeSet<Integer>();

  for(String num: ary){
if(!num.trim().equals("")){
set.add(new Integer(num.trim()));
}
} return set;
}