去除字符串中的空格\t、回車\n、換行符\r、製表符\tjava
public class StringUtils { public static void main(String[] args) { String billNo="12 3\n "; String billNo1="12 3\n "; String billNo2="12 3\n "; String billNo3="12 3 \n "; System.out.print(billNo+"|"+delSpace(billNo)+"|"+replaceBlank(billNo1)+"|"+"|"+replaceBlank2(billNo2)+"|"); System.out.print(billNo3.trim()); System.out.print(billNo3.replaceAll(" ","")); } /** * 使用Java正則表達式去除兩邊空格 * @param str * @return */ public static String delSpace(String str){ if(str==null) return null; String regStartSpace="^[ ]*"; String regEndSpace="[ ]*$"; String strDelSpace= str.replaceAll(regStartSpace,"").replaceAll(regEndSpace,""); return strDelSpace; } public static String replaceBlank(String str){ String destStr=""; if(str != null){ //其中\s能夠匹配空格、製表符、換行符等空白字符 Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(str); destStr=m.replaceAll(""); } return destStr; } public static String replaceBlank2(String str){ String destStr=""; if(str != null){ Pattern p = Pattern.compile("[\\s*|\t|\r|\n]*$"); Matcher m = p.matcher(str); destStr=m.replaceAll(""); } return destStr; } }