//正則匹配表達式 String regExOne = "^[1-9]{1}$"; String regExTow = "^[0-9]{2}$"; Pattern patternOne = Pattern.compile(regExOne); Pattern patternTow = Pattern.compile(regExTow); List<String> nameList = new ArrayList<>(); nameList.add("7號樁"); nameList.add("9號樁"); nameList.add("1號樁"); nameList.add("3號樁"); nameList.add("11號樁"); nameList.add("11號樁"); nameList.add("8號樁"); nameList.add("2號樁"); nameList.add("4號樁"); nameList.add("6號樁"); //建立map設置每一個元素的位置對於的值 Map<String,Integer> map = new HashMap<>(); //截取後的數據數字數組 int[] arrs = new int[nameList.size()]; for(int i=0,size = nameList.size();i<size;i++){ String name = nameList.get(i); //取出第第一位,驗證是不是數字 String nameIndexOne = name.substring(0,1); //驗證是否存在名稱中是否存在數字 Matcher matcherIndexOne = patternOne.matcher(nameIndexOne); boolean indexOne = matcherIndexOne.find(); if(indexOne){ //取出第第二位,驗證是不是數字 String nameIndexTow = name.substring(0,2); Matcher matcherIndexTow = patternTow.matcher(nameIndexTow); boolean indexTow = matcherIndexTow.find(); if(indexTow){ map.put(nameIndexTow,i); arrs[i] = Integer.parseInt(nameIndexTow); }else{ map.put(nameIndexOne,i); arrs[i] = Integer.parseInt(nameIndexOne); } } } Arrays.sort(arrs); for(int j=0,size=arrs.length;j<size;j++){ System.out.print(arrs[i]); }
// 判斷一個字符串是否含有數字 public boolean HasDigit(String content) { boolean flag = false; Pattern p = Pattern.compile(".*\\d+.*"); Matcher m = p.matcher(content); if (m.matches()) { flag = true; } return flag; }
//判斷一個字符是否都爲數字 public static boolean isDigit(String strNum){ return strNum.matches("[0-9]{1,}"); } // 判斷一個字符串是否都爲數字 public static boolean isDigit2(String strNum) { Pattern pattern = Pattern.compile("[0-9]{1,}"); Matcher matcher = pattern.matcher((CharSequence) strNum); return matcher.matches(); }
//截取數字 【讀取字符串中第一個連續的字符串,不包含後面不連續的數字】 public static String getNumbers(String content) { Pattern pattern = Pattern.compile("\\d+"); Matcher matcher = pattern.matcher(content); while (matcher.find()) { return matcher.group(0); } return ""; } // 截取非數字 public static String splitNotNumber(String content) { Pattern pattern = Pattern.compile("\\D+"); Matcher matcher = pattern.matcher(content); while (matcher.find()) { return matcher.group(0); } return ""; }
用java自帶函數 //判斷一個字符串是否爲數字 public static boolean isNumeric(String str){ for (int i = str.length(); --i>=0;) { if(!Character.isDigit(str.charAt(i))){ return false; } } return true; }
//判斷一個字符串是否爲數字 用ASCII碼 public static boolean isNumeric3(String str){ for(int i=str.length(); --i>=0;){ char c=str.charAt(i); if (c < 48 || c > 57) return false; } return true; }
//正則 public static boolean isNumeric2(String str){ Pattern pattern=Pattern.compile("[0-9]*"); return pattern.matcher(str).matches(); }