package com.jm.label.tools;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
?* 讀取字符串中的數字和小數
?* @author JM.H
?*
?*/
public class DigitUtil {
?? ?public static String getNumber(String str){
?? ??? ?Pattern p = Pattern.compile("(\\d+)");
?? ??? ?Matcher m = p.matcher(str); String result = "";
?? ??? ?if (m.find()) {
?? ??? ??? ?Map<Integer, String> map = new TreeMap<Integer, String>();
?? ??? ??? ?Pattern p2 = Pattern.compile("(\\d+\\.\\d+)");
?? ??? ??? ?m = p2.matcher(str); //遍歷小數部分
?? ??? ??? ?while (m.find()) {
?? ??? ??? ??? ?result = m.group(1) == null ? "" : m.group(1);
?? ??? ??? ??? ?int i = str.indexOf(result);
?? ??? ??? ??? ?String s = str.substring(i, i + result.length());
?? ??? ??? ??? ?map.put(i, s); //排除小數的整數部分和另一個整數相同的情況下,尋找整數位置出現錯誤的可能,還有就是尋找重復的小數 // 例子中是排除第二個345.56時第一個345.56產生干擾和尋找整數345的位置時,前面的小數345.56會干擾
?? ??? ??? ??? ?str = str.substring(0, i) + str.substring(i + result.length()); } //遍歷整數
?? ??? ??? ?Pattern p3 = Pattern.compile("(\\d+)");
?? ??? ??? ?m = p3.matcher(str);
?? ??? ??? ?while (m.find()) {
?? ??? ??? ??? ?result = m.group(1) == null ? "" : m.group(1); int i = str.indexOf(result); //排除jia567.23.23在第一輪過濾之后留下來的jia.23對整數23產生干擾
//?? ??? ??? ??? ?System.out.println(String.valueOf(str.charAt(i)));
?? ??? ??? ??? ?if (String.valueOf(str.charAt(i)).equals(".")) { //將這個字符串刪除
?? ??? ??? ??? ??? ?str = str.substring(0, i - 1) + str.substring(i + result.length());
?? ??? ??? ??? ??? ?continue;
?? ??? ??? ??? ?}
?? ??? ??? ??? ?String s = str.substring(i, i + result.length());
?? ??? ??? ??? ?map.put(i, s);
?? ??? ??? ??? ?str = str.substring(0, i) + str.substring(i + result.length());
?? ??? ??? ?}
?? ??? ??? ?result = "";
?? ??? ??? ?for (Map.Entry<Integer, String> e : map.entrySet()) {
?? ??? ??? ??? ?result += e.getValue() + ",";
?? ??? ??? ?}
?? ??? ??? ?result = result.substring(0, result.length()-1);
?? ??? ?}
?? ??? ?else {
?? ??? ??? ?result = "";
?? ??? ?}
//?? ??? ?System.out.println(result);
?? ??? ?String[] split = result.split(","); //
?? ??? ?String resultRtr = split[split.length-1]; //
?? ??? ?return resultRtr;
?? ?}
}
轉載于:https://www.cnblogs.com/java-h/p/10583986.html