正则表达式在Java中的使用

正则表达式在Java中的使用不仅限于String类中的match()方法!!!

正则中的^与$

首先我们来了解这两个符号在正则表达式中的作用:

^ 符号放在表达式头部表示开始匹配

$符号放在尾部表示结束匹配

如果同时携带^与$符,表示整体匹配,$后面如果再携带其他东西,是会匹配失败的

整体匹配失败

如果不携带$则表示部分部分匹配,如图:

结论:以$结尾的正则只能匹配一个字符串,反之可以匹配多个字符串。

String的matches方法与上文的异同

来看这几组匹配结果:

String regular = "^/(?<org>[^/]+)/(?<app>[^/]+)/pattern$";
String example = "/org/app/pattern";
System.out.println(example.matches(regular));//true
String regular = "^/(?<org>[^/]+)/(?<app>[^/]+)/pattern$";
String example = "/org/app/pattern123";
System.out.println(example.matches(regular));//false
String regular = "^/(?<org>[^/]+)/(?<app>[^/]+)/pattern";
String example = "/org/app/pattern123";
System.out.println(example.matches(regular));//false

与上文中正则匹配的异同就在于,当没有$结尾的时候,正常的正则匹配显示的是部分匹配。而Spring中的match方法给出的匹配结果是false。所以如果遇到这种场景,使用String的match方法很有可能出问题

Java中的Pattern

使用Pattern编译正则表达式之后再进行match就可以规避String中match方法出现的问题,直接看代码

String regular = "^/(?<org>[^/]+)/(?<app>[^/]+)/pattern";
String example = "/org/app/pattern123";
System.out.println(example.matches(regular));//false

Pattern compile = Pattern.compile(regular);
Matcher matcher = compile.matcher(example);
boolean isMatch = matcher.find();
System.out.println(isMatch);//true

使用group方法来提取匹配结果

String regular = "^/(?<org>[^/]+)/(?<app>[^/]+)/pattern";
String example = "/org/app/pattern123";
System.out.println(example.matches(regular));//false

Pattern compile = Pattern.compile(regular);
Matcher matcher = compile.matcher(example);
boolean isMatch = matcher.find();
System.out.println(isMatch);//true
System.out.println(matcher.group(0));// /org/app/pattern
System.out.println(matcher.group(1));//org
System.out.println(matcher.group(2));//app
System.out.println(matcher.group("app"));//app
System.out.println(matcher.group("org"));//org
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值