package com.mafei.utils;import java.util.regex.Pattern;public class StrUtil { private final static Pattern LTRIM = Pattern.compile("^\\s+"); private final static Pattern RTRIM = Pattern.compile("\\s+$"); private final static Pattern ATRIM = Pattern.compile("\\s+"); /** * 去除字符串两边的空白 * @param s * @return */ public static String trim(String s) { return s == null ? null : s.trim(); } /** * 去除字符串开头的空白 * @param s * @return */ public static String ltrim(String s) { return s == null ? null : LTRIM.matcher(s).replaceAll(""); } /** * 去除字符串结尾的空白 * @param s * @return */ public static String rtrim(String s) { return s == null ? null : RTRIM.matcher(s).replaceAll(""); } /** * 去除字符串中所有的空白 * @param s * @return */ public static String atrim(String s) { return s == null ? null : ATRIM.matcher(s).replaceAll(""); } /** * 如果字符串为null则返回空字符串,否则返回去除两边空白后的字符串 * @param s * @return */ public static String trimToEmpty(String s) { return s == null ? "" : trim(s); } /** * 去除两边空白后如果是空字符串则返回null,否则返回去除两边空白后的字符串 * @param s * @return */ public static String trimToNull(String s) { String trimStr = trim(s); return "".equals(trimStr) ? null : trimStr; }}