stringUtils 字串工具類
阿新 • • 發佈:2019-02-08
import com.google.common.collect.Lists; import org.apache.commons.lang3.StringEscapeUtils; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import org.springframework.web.servlet.LocaleResolver; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.File; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.URLDecoder; import java.net.URLEncoder; import java.text.CharacterIterator; import java.text.StringCharacterIterator; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 字串工具類, 繼承org.apache.commons.lang3.StringUtils類 */ public class StringUtils extends org.apache.commons.lang3.StringUtils { private static final char SEPARATOR = '_'; private static final String CHARSET_NAME = "UTF-8"; /** * 轉換為位元組陣列 * * @param str * @return */ public static byte[] getBytes(String str) { if (str != null) { try { return str.getBytes(CHARSET_NAME); } catch (UnsupportedEncodingException e) { return null; } } else { return null; } } /** * 位元組陣列轉換為String * * @param bytes * @return */ public static String toString(byte[] bytes) { try { return new String(bytes, CHARSET_NAME); } catch (UnsupportedEncodingException e) { return EMPTY; } } /** * 是否包含字串 * * @param str 驗證字串 * @param strs 字串組 * @return 包含返回true */ public static boolean inString(String str, String... strs) { if (str != null) { for (String s : strs) { if (str.equals(trim(s))) { return true; } } } return false; } /** * 替換掉HTML標籤方法 */ public static String unescapeHtml(String html) { if (isBlank(html)) { return ""; } return StringEscapeUtils.unescapeHtml4(html); } /** * 特殊符號轉義 防 跨站指令碼攻擊 * * @param aText * @return */ public static String HTMLEncode(String aText) { final StringBuilder result = new StringBuilder(); final StringCharacterIterator iterator = new StringCharacterIterator(aText); char character = iterator.current(); while (character != CharacterIterator.DONE) { if (character == '<') { result.append("<"); } else if (character == '>') { result.append(">"); } else if (character == '&') { result.append("&"); } else if (character == '\"') { result.append("""); } else { //the char is not a special one //add it to the result as is result.append(character); } character = iterator.next(); } return result.toString(); } /** * 替換掉HTML標籤方法 */ public static String replaceHtml(String html) { if (isBlank(html)) { return ""; } String regEx = "<.+?>"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(html); String s = m.replaceAll(""); return s; } /** * 替換為手機識別的HTML,去掉樣式及屬性,保留回車。 * * @param html * @return */ public static String replaceMobileHtml(String html) { if (html == null) { return ""; } return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>"); } /** * 替換為手機識別的HTML,去掉樣式及屬性,保留回車。 * * @param txt * @return */ public static String toHtml(String txt) { if (txt == null) { return ""; } return replace(replace(EncodesUitls.escapeHtml(txt), "\n", "
"), "\t", " "); } /** * 縮略字串(不區分中英文字元) * * @param str 目標字串 * @param length 擷取長度 * @return */ public static String abbr(String str, int length) { if (str == null) { return ""; } try { StringBuilder sb = new StringBuilder(); int currentLength = 0; for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) { currentLength += String.valueOf(c).getBytes("GBK").length; if (currentLength <= length - 3) { sb.append(c); } else { sb.append("..."); break; } } return sb.toString(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return ""; } public static String abbr2(String param, int length) { if (param == null) { return ""; } StringBuffer result = new StringBuffer(); int n = 0; char temp; boolean isCode = false; // 是不是HTML程式碼 boolean isHTML = false; // 是不是HTML特殊字元,如 for (int i = 0; i < param.length(); i++) { temp = param.charAt(i); if (temp == '<') { isCode = true; } else if (temp == '&') { isHTML = true; } else if (temp == '>' && isCode) { n = n - 1; isCode = false; } else if (temp == ';' && isHTML) { isHTML = false; } try { if (!isCode && !isHTML) { n += String.valueOf(temp).getBytes("GBK").length; } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } if (n <= length - 3) { result.append(temp); } else { result.append("..."); break; } } // 取出擷取字串中的HTML標記 String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2"); // 去掉不需要結素標記的HTML標記 temp_result = temp_result .replaceAll( "?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>", ""); // 去掉成對的HTML標記 temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)\\1>", "$2"); // 用正則表示式取出標記 Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>"); Matcher m = p.matcher(temp_result); List endHTML = Lists.newArrayList(); while (m.find()) { endHTML.add(m.group(1)); } // 補全不成對的HTML標記 for (int i = endHTML.size() - 1; i >= 0; i--) { result.append(""); result.append(endHTML.get(i)); result.append(">"); } return result.toString(); } /** * 轉換為Double型別 */ public static Double toDouble(Object val) { if (val == null) { return 0D; } try { return Double.valueOf(trim(val.toString())); } catch (Exception e) { return 0D; } } /** * 轉換為Float型別 */ public static Float toFloat(Object val) { return toDouble(val).floatValue(); } /** * 轉換為Long型別 */ public static Long toLong(Object val) { return toDouble(val).longValue(); } /** * 轉換為Integer型別 */ public static Integer toInteger(Object val) { return toLong(val).intValue(); } /** * 獲得使用者遠端地址 */ public static String getRemoteAddr(HttpServletRequest request) { String remoteAddr = request.getHeader("X-Real-IP"); if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("X-Forwarded-For"); } else if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("Proxy-Client-IP"); } else if (isNotBlank(remoteAddr)) { remoteAddr = request.getHeader("WL-Proxy-Client-IP"); } return remoteAddr != null ? remoteAddr : request.getRemoteAddr(); } /** * 獲得使用者遠端IP地址 Mac地址 */ public static String getMACAddress(String ip) { String result = ""; String[] cmd = { "cmd", "/c", "ping " + ip }; String[] another = { "cmd", "/c", "arp -a" }; String cmdResult = callCmd(cmd, another); result = filterMacAddress(ip, cmdResult, "-"); return result; } /** * @param cmd 第一個命令 * @param another 第二個命令 * @return 第二個命令的執行結果 */ public static String callCmd(String[] cmd, String[] another) { String result = ""; String line = ""; try { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(cmd); proc.waitFor(); //已經執行完第一個命令,準備執行第二個命令 proc = rt.exec(another); InputStreamReader is = new InputStreamReader(proc.getInputStream()); BufferedReader br = new BufferedReader(is); while ((line = br.readLine()) != null) { result += line; } } catch (Exception e) { e.printStackTrace(); } return result; } /** * @param ip 目標ip,一般在區域網內 * @param sourceString 命令處理的結果字串 * @param macSeparator mac分隔符號 * @return mac地址,用上面的分隔符號表示 */ public static String filterMacAddress(final String ip, final String sourceString, final String macSeparator) { String result = ""; String regExp = "((([0-9,A-F,a-f]{1,2}" + macSeparator + "){1,5})[0-9,A-F,a-f]{1,2})"; Pattern pattern = Pattern.compile(regExp); Matcher matcher = pattern.matcher(sourceString); while (matcher.find()) { result = matcher.group(1); if (sourceString.indexOf(ip) <= sourceString.lastIndexOf(matcher.group(1))) { break; //如果有多個IP,只匹配本IP對應的Mac. } } return result; } /** * 駝峰命名法工具 * * @return toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCamelCase(String s) { if (s == null) { return null; } s = s.toLowerCase(); StringBuilder sb = new StringBuilder(s.length()); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == SEPARATOR) { upperCase = true; } else if (upperCase) { sb.append(Character.toUpperCase(c)); upperCase = false; } else { sb.append(c); } } return sb.toString(); } /** * 駝峰命名法工具 * * @return toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toCapitalizeCamelCase(String s) { if (s == null) { return null; } s = toCamelCase(s); return s.substring(0, 1).toUpperCase() + s.substring(1); } /** * 駝峰命名法工具 * * @return toCamelCase("hello_world") == "helloWorld" * toCapitalizeCamelCase("hello_world") == "HelloWorld" * toUnderScoreCase("helloWorld") = "hello_world" */ public static String toUnderScoreCase(String s) { if (s == null) { return null; } StringBuilder sb = new StringBuilder(); boolean upperCase = false; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); boolean nextUpperCase = true; if (i < (s.length() - 1)) { nextUpperCase = Character.isUpperCase(s.charAt(i + 1)); } if ((i > 0) && Character.isUpperCase(c)) { if (!upperCase || !nextUpperCase) { sb.append(SEPARATOR); } upperCase = true; } else { upperCase = false; } sb.append(Character.toLowerCase(c)); } return sb.toString(); } /** * 如果不為空,則設定值 * * @param target * @param source */ public static String setValueIfNotBlank(String target, String source) { if (isNotBlank(source)) { target = source; } return target; } /** * 轉換為JS獲取物件值,生成三目運算返回結果 * * @param objectString 物件串 * 例如:row.user.id * 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id */ public static String jsGetVal(String objectString) { StringBuilder result = new StringBuilder(); StringBuilder val = new StringBuilder(); String[] vals = split(objectString, "."); for (int i = 0; i < vals.length; i++) { val.append("." + vals[i]); result.append("!" + (val.substring(1)) + "?'':"); } result.append(val.substring(1)); return result.toString(); } /** * 轉換為路徑為當前系統識別的路徑 * * @param value 物件串 * 例如:/zotech/house/room 或 \zotech\house\room * 返回:windows下:\zotech\house\room linuxl下:/zotech/house/room */ public static String convertPath(String value) { value = StringUtils.replaceEach(value, new String[]{"///", "//", "/", "\\\\\\", "\\\\", "\\"}, new String[]{File.separator, File.separator, File.separator, File.separator, File.separator, File.separator}); return StringUtils.replaceEach(value, new String[]{"///", "//", "/", "\\\\\\", "\\\\", "\\"}, new String[]{File.separator, File.separator, File.separator, File.separator, File.separator, File.separator}); } /** * 轉換中文為UTF-8 * * @param value 物件串 */ public static String Chinese2UTF8(String value) { char[] ch = value.toCharArray(); String str = ""; for (int i = 0; i < ch.length; i++) { if (isChinese(ch[i])) { try { str += URLEncoder.encode(ch[i] + "", "UTF-8"); } catch (Exception e) { e.printStackTrace(); } } else { str += ch[i]; } } return str; } /** * 轉換中文為UTF-8 * * @param value 物件串 */ public static String UTF82Chinese(String value) { if (StringUtils.isBlank(value)) { return ""; } try { String str = URLDecoder.decode(value, "UTF-8"); return str; } catch (Exception e) { e.printStackTrace(); return ""; } } /** * 根據Unicode編碼完美的判斷中文漢字和符號 * * @param c * @return */ private static boolean isChinese(char c) { Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) { return true; } return false; } /** * 完整的判斷中文漢字和符號 * * @param strName * @return */ public static boolean isChinese(String strName) { char[] ch = strName.toCharArray(); for (int i = 0; i < ch.length; i++) { char c = ch[i]; if (isChinese(c)) { return true; } } return false; } /** * ==================================== 漢語數字大寫轉換 ============================================================= * * */ /** * 漢語中數字大寫 */ private static final String[] CN_UPPER_NUMBER = { "零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖" }; /** * 漢語中貨幣單位大寫 */ private static final String[] CN_UPPER_MONETRAY_UNIT = { "分", "角", "元", "拾", "佰", "仟", "萬", "拾", "佰", "仟", "億", "拾", "佰", "仟", "兆", "拾", "佰", "仟" }; /** * 特殊字元:整 */ private static final String CN_FULL = "整"; /** * 特殊字元:負 */ private static final String CN_NEGATIVE = "負"; /** * 金額的精度,預設值為2 */ private static final int MONEY_PRECISION = 2; /** * 特殊字元:零元整 */ private static final String CN_ZEOR_FULL = "零元" + CN_FULL; /** * 把輸入的金額轉換為漢語中人民幣的大寫 * @param numberOfMoney 輸入的金額 * @return 對應的漢語大寫 */ public static String numberToCNMontrayUnit(BigDecimal numberOfMoney) { StringBuffer sb = new StringBuffer(); // -1, 0, or 1 as the value of this BigDecimal is negative, zero, or // positive. int signum = numberOfMoney.signum(); // 零元整的情況 if (signum == 0) { return CN_ZEOR_FULL; } //這裡會進行金額的四捨五入 long number = numberOfMoney.movePointRight(MONEY_PRECISION) .setScale(0, 4).abs().longValue(); // 得到小數點後兩位值 long scale = number % 100; int numUnit = 0; int numIndex = 0; boolean getZero = false; // 判斷最後兩位數,一共有四中情況:00 = 0, 01 = 1, 10, 11 if (!(scale > 0)) { numIndex = 2; number = number / 100; getZero = true; } if ((scale > 0) && (!(scale % 10 > 0))) { numIndex = 1; number = number / 10; getZero = true; } int zeroSize = 0; while (true) { if (number <= 0) { break; } // 每次獲取到最後一個數 numUnit = (int) (number % 10); if (numUnit > 0) { if ((numIndex == 9) && (zeroSize >= 3)) { sb.insert(0, CN_UPPER_MONETRAY_UNIT[6]); } if ((numIndex == 13) && (zeroSize >= 3)) { sb.insert(0, CN_UPPER_MONETRAY_UNIT[10]); } sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]); sb.insert(0, CN_UPPER_NUMBER[numUnit]); getZero = false; zeroSize = 0; } else { ++zeroSize; if (!(getZero)) { sb.insert(0, CN_UPPER_NUMBER[numUnit]); } if (numIndex == 2) { if (number > 0) { sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]); } } else if (((numIndex - 2) % 4 == 0) && (number % 1000 > 0)) { sb.insert(0, CN_UPPER_MONETRAY_UNIT[numIndex]); } getZero = true; } // 讓number每次都去掉最後一個數 number = number / 10; ++numIndex; } // 如果signum == -1,則說明輸入的數字為負數,就在最前面追加特殊字元:負 if (signum == -1) { sb.insert(0, CN_NEGATIVE); } // 輸入的數字小數點後兩位為"00"的情況,則要在最後追加特殊字元:整 if (!(scale > 0)) { sb.append(CN_FULL); } return sb.toString(); } }