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; } } }
原文:https://www.cnblogs.com/paranoidCAT/p/10910565.html