All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.yixan.tools.common.util.StringUtil Maven / Gradle / Ivy

There is a newer version: 3.7.1
Show newest version
/*
 * 文  件  名:StringUtil.java
 * 版         权:Copyright 2012 JESHING Tech.Co.Ltd.All Rights Reserved.
 * 描         述:
 * 修  改  人:王波
 * 修改时间:2014-3-15
 * 修改内容:新增
 */
package com.yixan.tools.common.util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * 字符串工具类
 *
 * @author 王波
 * @version C01 2014-3-16
 * @since v1.0
 */
public final class StringUtil {

    /**
     * 数字正则表达式
     */
    private static final Pattern DIGIT = Pattern.compile("([0-9]*)");

    /**
     * 手机正则表达式
     */
    private static final Pattern PHONE = Pattern.compile("(1\\d{2})(\\d{4})(\\d{4})");

    /**
     * 身份证正则表达式
     */
    private static final Pattern IDCARD = Pattern
            .compile("(^[1-9][0-9]{5}(19[0-9]{2}|20[01][0-9])(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])[0-9]{3}[0-9xX]$)");

    /**
     * 邮箱正则表达式
     */
    private static final Pattern EMAIL = Pattern.compile("([-\\.\\w]+)(@)([-\\.\\w]+\\.\\w+)");

    /**
     * 网址正则表达式
     */
    private static final Pattern URL = Pattern.compile("^https?://.*");

    /**
     * 正则表达式转义字符
     */
    private static final Pattern REG_CHAR = Pattern.compile("([\\{\\}\\[\\]\\(\\)\\^\\$\\.\\*\\?\\-\\+\\\\])");

    /**
     * 字符串分隔符正则表达式
     */
    private static final Pattern SEPARATOR = Pattern.compile("\\|");

    /**
     * 构造函数
     */
    private StringUtil() {
    }

    /**
     * 判断字符串是不是手机号码
     *
     * @author zhaohuihua
     * @param str 字符串
     * @return 是不是手机号码, 如果字符串等于null或空字符串, 返回false
     */
    public static boolean isPhone(String str) {
        if (str == null || str.length() == 0) {
            return false;
        }
        return PHONE.matcher(str).matches();
    }

    /**
     * 验证是否为有效的身份证号
     * 
     * @author luyujian
     * @param str 参数
     * @return true:是 | false:否
     */
    public static boolean isIDCard(String str) {
        if (str == null || str.length() == 0) {
            return false;
        }
        return IDCARD.matcher(str).matches();
    }

    /**
     * 判断字符串是不是邮箱地址
     *
     * @author zhaohuihua
     * @param str 字符串
     * @return 是不是邮箱地址, 如果字符串等于null或空字符串, 返回false
     */
    public static boolean isEmail(String str) {
        if (str == null || str.length() == 0) {
            return false;
        }
        return EMAIL.matcher(str).matches();
    }

    /**
     * 判断字符串是不是网址
     *
     * @author zhaohuihua
     * @param str 字符串
     * @return 是不是网址, 如果字符串等于null或空字符串, 返回false
     */
    public static boolean isUrl(String str) {
        if (str == null || str.length() == 0) {
            return false;
        }
        return URL.matcher(str).matches();
    }

    /**
     * 判断字符串是不是数字
     *
     * @author zhaohuihua
     * @param str 字符串
     * @return 是不是数字, 如果字符串等于null或空字符串, 返回false
     */
    public static boolean isDigit(String str) {
        if (str == null || str.length() == 0) {
            return false;
        }
        return DIGIT.matcher(str).matches();
    }

    /**
     * 判断string是否为null,或长度是否为0
     *
     * @param str 待判断的字符串
     *
     * @return 如果字符串为null,或长度为0,则返回true,否则返回false
     */
    public static boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

    /**
     * 判断string是否不为null并且长度大于0
     *
     * @param str 待判断的字符串
     *
     * @return 如果字符串不为null并且长度大于0,则返回true,否则返回false
     */
    public static boolean isNotEmpty(String str) {
        return str != null && str.length() > 0;
    }

    /**
     * 判断string数组是否存在空字符串(null,或长度为0)
     *
     * @author 赵卉华
     * @param str 待判断的字符串数组
     *
     * @return 如果存在空字符串,则返回true,否则返回false
     */
    public static boolean isAnyEmpty(String... str) {
        for (String s : str) {
            if (null == s || s.length() == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断两个字符串是不是相等
     *
     * @author zhaohuihua
     * @param o
     * @param n
     * @return
     */
    public static boolean equals(String o, String n) {
        if (o == null && n == null) {
            return true;
        } else if (o == null && n != null || o != null && n == null) {
            return false;
        } else {
            return o.equals(n);
        }
    }

    /**
     * 格式化, 实现参数替换
     *
     * @author 赵卉华
     * @param string 原字符串
     * @param param 参数键值对
     * @return 参数替换后的字符串
     */
    public static String format(String string, Map params) {
        if (string == null || params == null) {
            return string;
        }
        for (Map.Entry item : params.entrySet()) {
            String temp = item.getKey().trim();
            String key;
            if (temp.startsWith("{") && temp.endsWith("}")) {
                key = temp;
            } else {
                key = "{" + temp + "}";
            }
            // 替换正则表达式的转义字符, KEY不需要支持正则表达式
            // 如果不替换, user.id这个点就会成为通配符
            key = REG_CHAR.matcher(key).replaceAll("\\\\$1");

            Object object = item.getValue();
            String value = object == null ? "" : object.toString();
            string = string.replaceAll(key, value);
        }
        return string;
    }

    /**
     * 格式化, 实现参数替换
     *
     * @author 赵卉华
     * @param string 原字符串
     * @param param 参数键值对, 参数个数必须是2的倍数
     * @return 参数替换后的字符串
     */
    public static String format(String string, Object... params) {
        if (string == null || params == null || params.length == 0) {
            return string;
        }

        if (params.length % 2 != 0) {
            throw new IllegalArgumentException("参数必须是键值对, 参数个数必须是2的倍数");
        }

        Map map = new HashMap();
        for (int i = 0; i < params.length;) {
            map.put(params[i++].toString(), params[i++]);
        }
        return format(string, map);
    }

    /**
     * 拆分字符串, 以竖杠|为分隔符
* 每一个子字符串都已经trim()过了
* "aa|bb|cc" --> [aa, bb, cc]
* "aa|bb||cc" --> [aa, bb, , cc] * * @param string 原字符串 * @return 拆分的字符串数组 */ public static String[] split(String string) { if (string == null) { return null; } String[] array = SEPARATOR.split(string); for (int i = 0; i < array.length; i++) { array[i] = array[i].trim(); } return array; } public static String remove(String string, int start, int end) { if (string == null) { return null; } StringBuilder buffer = new StringBuilder(); if (start > 0) { buffer.append(string.substring(0, start)); } if (end < string.length()) { buffer.append(string.substring(end)); } return buffer.toString(); } /** * 超过指定长度则省略中间字符, 如果未超过指定长度则返回原字符, length小于20时省略最后部分而不是中间部分
* 如: 诺贝尔奖是以瑞典著名的 ... 基金创立的 * * @author 赵卉华 * @param text 长文本 * @param length 指定长度 * @return 省略中间部分的字符 */ public static String ellipsis(String text, int length) { if (text == null || text.length() <= length) { return text; } String flag = " ... "; if (length < 20) { return text.substring(0, length) + flag; } int suffix = (length - flag.length()) / 4; int prefix = length - flag.length() - suffix; int end = text.length() - suffix; return text.substring(0, prefix) + flag + text.substring(end); } /** * 隐藏手机号码或邮箱, 如果不是手机号码和邮箱, 返回原字符串 * * @author 赵卉华 * @param text 手机号码或邮箱 * @return 隐藏后的字符串, 如: 139****1382, zh****[email protected] */ public static String hidden(String text) { if (isEmpty(text)) { return text; } String hide = "****"; Matcher phone = PHONE.matcher(text); if (phone.matches()) { return phone.group(1) + hide + phone.group(3); } Matcher email = EMAIL.matcher(text); if (email.matches()) { String prefix = email.group(1); String at = email.group(2); String suffix = email.group(3); String temp; if (prefix.length() >= 4) { temp = prefix.substring(0, 2) + hide + prefix.substring(prefix.length() - 2); } else if (prefix.length() >= 2) { temp = prefix.substring(0, 1) + hide + prefix.substring(1); } else { temp = prefix + hide + prefix; } return temp + at + suffix; } return text; } /** * 根据手机号码或邮箱生成随机的昵称
* 如果原字符串为空, 返回原字符串
* 如果不是手机号码和邮箱, 返回原字符串+4位随机大写字母
* 如: 13913001382=139ADGK1382, [email protected]=zhaohuihuaQETU * * @author 赵卉华 * @param text 手机号码或邮箱 * @return 随机昵称 */ public static String generateRandomNickname(String text) { if (isEmpty(text)) { return text; } // 4位随机大写字母 String random = RandomUtil.generateString(4).toUpperCase(); Matcher phone = PHONE.matcher(text); if (phone.matches()) { return phone.group(1) + random + phone.group(3); } Matcher email = EMAIL.matcher(text); if (email.matches()) { return email.group(1) + random; } return text + random; } /** *

* Capitalizes a String changing the first letter to title case as per {@link Character#toTitleCase(char)}. No other * letters are changed. *

* *

* For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#capitalize(String)}. A * {@code null} input String returns {@code null}. *

* *
     * StringUtils.capitalize(null)  = null
     * StringUtils.capitalize("")    = ""
     * StringUtils.capitalize("cat") = "Cat"
     * StringUtils.capitalize("cAt") = "CAt"
     * 
* * @param str the String to capitalize, may be null * @return the capitalized String, {@code null} if null String input * @see org.apache.commons.lang3.text.WordUtils#capitalize(String) * @since 2.0 */ public static String capitalize(final String str) { int strLen; if (str == null || (strLen = str.length()) == 0) { return str; } char firstChar = str.charAt(0); if (Character.isTitleCase(firstChar)) { // already capitalized return str; } return new StringBuilder(strLen).append(Character.toTitleCase(firstChar)).append(str.substring(1)).toString(); } /** 左侧补零 **/ public static String pad(int number, int length) { return pad(String.valueOf(number), '0', true, length); } /** 左侧补零 **/ public static String pad(long number, int length) { return pad(String.valueOf(number), '0', true, length); } /** 左侧补空格 **/ public static String pad(String string, int length) { return pad(string, ' ', true, length); } /** * 左侧补字符
* pad("12345", '_', 10) 返回 _____12345
* * @param string * @param c * @param length * @return */ public static String pad(String string, char c, int length) { return pad(string, c, true, length); } /** * 左侧或右侧补字符
* pad("12345", '_', false, 10) 返回 12345_____
* * @param string * @param c * @param left 左侧补(true)还是右侧补(false) * @param length * @return */ public static String pad(String string, char c, boolean left, int length) { if (string == null || string.length() >= length) { return string; } char[] array = new char[length - string.length()]; Arrays.fill(array, c); return left ? new String(array) + string : string + new String(array); } /** * 统计子字符串出现次数 * * @param string 源字符串 * @param substring 子字符串 * @return 次数 */ public static int countSubstring(String string, String substring) { int count = 0; for (int i = 0; (i = string.indexOf(substring, i)) >= 0; i += substring.length()) { count++; } return count; } /** * 将对象转换为日志文本
* 如 toLogs(params, operator) 返回 \n\t{"xxx":"" * * @param objects * @return */ public static String toLogs(Object... objects) { StringBuilder buffer = new StringBuilder(); for (Object object : objects) { buffer.append("\n\t").append(toJsonString(object)); } return buffer.toString(); } public static String toJsonString(Object object) { if (object == null) { return "null"; } else if (object instanceof String) { return (String) object; } try (SerializeWriter out = new SerializeWriter()) { JSONSerializer serializer = new JSONSerializer(out); serializer.config(SerializerFeature.QuoteFieldNames, false); serializer.config(SerializerFeature.WriteDateUseDateFormat, true); serializer.write(object); return out.toString(); } } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy