首页 > 其他 > 详细

RegexpUtil工具类

时间:2019-05-23 11:01:28      阅读:175      评论:0      收藏:0      [点我收藏+]
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 处理正则表达式的工具类
 * 一方库依赖:无
 * 二方库依赖:无
 * 三方库依赖:无
 *
 * @author ParanoidCAT
 * @since JDK 1.8
 */
public class RegexpUtil {
    /**
     * 原文中是否包含正则表达式表达的内容
     *
     * @param prototype 原文
     * @param regexp    正则表达式
     * @return true/false
     */
    public static boolean isRegularFind(String prototype, String regexp) {
        try {
            return Pattern.compile(regexp, Pattern.CASE_INSENSITIVE).matcher(prototype).find();
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 原文中是否全文匹配正则表达式表达的内容
     *
     * @param prototype 原文
     * @param regexp    正则表达式
     * @return true/false
     */
    public static boolean isRegularMatches(String prototype, String regexp) {
        try {
            return Pattern.compile(regexp, Pattern.CASE_INSENSITIVE).matcher(prototype).matches();
        } catch (Exception e) {
            return false;
        }
    }

    /***
     * 获取原文中包含正则表达式内容的部分
     *
     * @param prototype 原文
     * @param regexp 正则表达式
     * @param groupId 取值范围
     * @return java.lang.String
     */
    public static String getRegularFind(String prototype, String regexp, Integer groupId) {
        try {
            Matcher matcher = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE).matcher(prototype);
            return matcher.find() ? matcher.group(Optional.ofNullable(groupId).orElse(0)) : null;
        } catch (Exception e) {
            return null;
        }
    }

    /***
     * 获取原文中包含正则表达式内容的部分
     * 若原文中没有正则表达式内容则返回默认值
     *
     * @param prototype 原文
     * @param regexp 正则表达式
     * @param groupId 取值范围
     * @param defaultValue 默认值
     * @return java.lang.String
     */
    public static String getRegularFindOrDefault(String prototype, String regexp, Integer groupId, String defaultValue) {
        try {
            Matcher matcher = Pattern.compile(regexp, Pattern.CASE_INSENSITIVE).matcher(prototype);
            return matcher.find() ? matcher.group(Optional.ofNullable(groupId).orElse(0)) : defaultValue;
        } catch (Exception e) {
            return defaultValue;
        }
    }
}

 

RegexpUtil工具类

原文:https://www.cnblogs.com/paranoidCAT/p/10910565.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!