來源:有的時候,需要過濾字符串的格式,但是一個一個去尋找,又麻煩,我自己就記錄一點點,以後再碰到就更新
public static String htmlFilter(String htmlStr) {
String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; //定義script的正則表達式
String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; //定義style的正則表達式
// String regEx_html = "<[^>]+>"; //定義HTML標籤的正則表達式
String regEx_html = "(\\r\\n|\\r|\\n|\\n\\r)";
Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
Matcher m_script = p_script.matcher(htmlStr);
htmlStr = m_script.replaceAll(""); //過濾script標籤
Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
Matcher m_style = p_style.matcher(htmlStr);
htmlStr = m_style.replaceAll(""); //過濾style標籤
Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
Matcher m_html = p_html.matcher(htmlStr);
htmlStr = m_html.replaceAll(""); //過濾html標籤
return htmlStr;
}
這是 新加的:1、過濾回車和換行符
newString = myString.replaceAll("(\r\n|\r|\n|\n\r)", "<br>");
/*
* 如果是小數,保留兩位,非小數,保留整數
* @param number
*/
public static String getDoubleString(double number) {
String numberStr = "";
if (((int) number * 1000) == (int) (number * 1000)) {
//如果是一個整數
numberStr = String.valueOf((int) number);
} else {
DecimalFormat df = new DecimalFormat("######0.00");
numberStr = df.format(number);
}
return numberStr;
}
這個判斷字符串,是否有漢字,或者金額字符串處理的方法:
Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?[萬][人][民][幣]");
boolean blo1 = pattern1.matcher(amount).matches();
這個是判斷是否全爲數字,支持小數點:0.123 此類形式
/**
* 判斷一個字符串是否是數字。
*
* @param string
* @return
*/
public static boolean isNumber(String string) {
if (string == null)
return false;
Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");
return pattern.matcher(string).matches();
}