新手必看:正则表达式在Java中的使用
https://www.flypeng.com win10系统 发布时间:2023-04-20 10:27 来源:未知

正则表达式在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

如果你有好的win10资讯或者win10教程,以及win10相关的问题想要获得win10系统下载的关注与报道。
欢迎加入发送邮件到#qq.com(#替换为@)。期待你的好消息!