包含中文和數字的字符串中提取數字

這兩天遇到一個問題,前端需要把包含數字和中文的字符串中的數字以紅色顯示,樓主查了一些關於正則表達式的東西,才得以解決

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {
    public static void main(String[] args) {
        //滿100減10  打8.5折   8折
        String s = "8折";
        Pattern p = Pattern.compile("[\\u4e00-\\u9fa5]+|\\d+\\.+\\d+|\\d+");
        Matcher m = p.matcher( s );
        Pattern pattern = Pattern.compile("-?[0-9]+(\\.[0-9]+)?");
        StringBuilder title = new StringBuilder();

        while ( m.find() ) {
            String group = m.group();
            if(pattern.matcher(group).matches()){
                title.append("<span style=\"color:red;\">");
                title.append(group);
                title.append("</span>");
            }else{
                title.append(group);
            }
        }
        System.out.println(title.toString());
    }
}

先用正則表達式把數字(整數和浮點)和中文區分開,然後在用正則對數字類型進行匹配,添加紅色顯示屬性,有不到之處盡請提出

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章