JAVA中使用正则表达式(java.util.regex.Pattern/Matcher)

在许多场景中,使用正则表达式往往能事半功倍,仅以此记录java中如何简单使用正则表达式

示例

public class RegexTest {
    public static void main(String[] args) {
        // 正则表达式:匹配非负整数的字符串
        String regexStr = "[0-9]+";
        // 待匹配的字符串
        String matStr = "09";

        regexTest(regexStr, matStr);
        regexTest2(regexStr, matStr);
    }

    public static void regexTest(String regexStr, String matStr){
        // 获取Pattern
        Pattern pt = Pattern.compile(regexStr);
        // 获取Matcher
        Matcher mt = pt.matcher(matStr);
        // 是否匹配
        boolean bl = mt.matches();
        System.out.println("是否非负整数:" + bl);
    }

    public static void regexTest2(String regexStr, String matStr){
        boolean matches = Pattern.matches(regexStr, matStr);
        System.out.println("一步到位,是否非负整数:" + matches);
    }

}

查看Pattern.matches(regexStr, matStr)源码
Pattern.matcher(regex, input)源码
注:Pattern和Matcher都是final修饰,不能直接new一个对象

  1. Pattern pt = Pattern.compile('正则表达式'):获取一个Pattern对象,可以理解为一个匹配模式;
  2. Matcher mt = pt.matcher('待校验的字符串'):获取一个Matcher对象,可以理解为一个匹配器;
  3. boolean bl = mt.matches();:返回匹配结果;
  4. boolean matches = Pattern.matches('正则表达式', '待校验字符串');:返回正则表达式匹配待校验字符串后的结果;

查看源码可知:表达式4 === 表达式1 + 表达式2 + 表达式3(当正则表达式需要重复使用时,则不建议使用表达式4)

补充:

Pattern的方法

  1. public static Pattern compile(String regex) 将给定的正则表达式编译成一个模式
  2. public Matcher matcher(CharSequence input) 创建一个匹配器,匹配给定的输入与此模式
  3. public static boolean matches(String regex, CharSequence input) 编译给定的正则表达式,并尝试匹配给定的输入;返回正则表达式是否匹配输入的结果
  4. public String pattern() 返回编译此模式的正则表达式

Matcher的方法

  1. public boolean matches() 尝试将整个区域与模式进行匹配
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值