package com.model.regexp; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/8/19 20:39 * 正则表达式应用实例 */ public class RegExpDemo05 { public static void main(String[] args) { String context="18348950824"; // 匹配汉字 // String regExp="^[\u0391-\uffe5]$"; // // 邮政编码:以1-9开头的六位数字 // String regExp="^[1-9]\\d{5}$"; // 手机号:以18,15,13,14开头的11位数 // String regExp="^1[3|4|5|8]\\d{9}$"; // url:匹配url String regExp="^((http|https)://)([\\w-]+\\.)+([\\w-])+(\\/[\\w-?=&%.#]*)?$"; Pattern pattern = Pattern.compile(regExp); Matcher matcher = pattern.matcher(context); while (matcher.find()){ System.out.println(matcher.group(0)); } } }
package com.model.regexp; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @Description:测试类 * @Author: 张紫韩 * @Crete 2021/8/19 23:22 * */ public class RegExpDemo06 { public static void main(String[] args) { // 1. 演示Pattern.matchers()方法的使用,整体匹配,查看是否匹配成功 // 只是返回是否匹配成功,不匹配截取返回子字符串 String context="hello world!"; String regExp="\\w"; // boolean matches = Pattern.matches(regExp, context); System.out.println(matches); // 2.演示Matcher方法的使用: String context1="hello world!"; String regExp1="\\w"; Pattern pattern = Pattern.compile(regExp1); Matcher matcher = pattern.matcher(context1); while (matcher.find()){ System.out.println(matcher.group(0)); System.out.println(matcher.end()); // 整体匹配,是否匹配成功 System.out.println(matcher.matches()); } // 3.replaceAll() 方法的使用,替换 // 如果 字符串中有 hello 就替换成 张紫韩 String context2="hello world!"; String regExp2="hello"; Pattern pattern2 = Pattern.compile(regExp2); Matcher matcher2 = pattern2.matcher(context2); String replaceAll = matcher2.replaceAll("张紫韩"); System.out.println(replaceAll); } }
原文:https://www.cnblogs.com/zzhAylm/p/15164561.html