這兩天遇到一個問題,前端需要把包含數字和中文的字符串中的數字以紅色顯示,樓主查了一些關於正則表達式的東西,才得以解決
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());
}
}
先用正則表達式把數字(整數和浮點)和中文區分開,然後在用正則對數字類型進行匹配,添加紅色顯示屬性,有不到之處盡請提出