Java Pattern和Matcher用法

Java正则表达式通过java.util.regex包下的Pattern和Matcher类实现

Pattern用法

Pattern类用于创建一个正则表达式,也可以说是创建一个匹配模式

//1. Pattern.compile()
Pattern pattern = Pattern.compile("Java");
// 返回此模式的正则表达式即Java
System.out.println(pattern.pattern());

//2. Pattern.split()
String test="123Java456Java789Java";
String[] result = pattern.split(test);
for(String s : result)
System.out.println(s);
//结果:
//123
//456
//789

//3. Pattern.matche()方法
String test1 = "Java";
String test2 = "Java123456";
System.out.println(Pattern.matches("Java",test1));//返回true
System.out.println(Pattern.matches("Java",test2));//返回false

Matcher类用法#

Pattern类中的matcher(CharSequence input)会返回一个Matcher对象。Matcher类提供了对正则表达式的分组支持,以及对正则表达式的多次匹配支持,要想得到更丰富的正则匹配操作,那就需要将Pattern与Matcher联合使用。

Matcher类提供了三个返回boolean值得匹配方法:matches(),lookingAt(),find(),find(int start),其中matches()用于全字符串匹配,lookingAt从字符串最开头开始匹配满足的子串,find可以对任意位置字符串匹配,其中start为起始查找索引值。

Pattern pattern = Pattern.compile("Java");
String test1 = "Java";
String test2 = "Java1234";
String test3 = "1234Java"

//1. match方法需要整个字符串都匹配正则才返回true
//1)返回true
Matcher matcher = pattern.matcher(test1);
System.out.println(matcher.matches());

//2)返回false
matcher = pattern.matcher(test2);
System.out.println(matcher.matches());

//2. lookingAt需要字符串是以正则模式开头,才返回true
//1)返回true
matcher = pattern.matcher(test2);
System.out.println(matcher.lookingAt());
//2)返回false
matcher = pattern.matcher(test3);
System.out.println(matcher.lookingAt());

//3.从相应的下标开始匹配,只要有匹配到的就返回true
//1)返回true
matcher = pattern.matcher(test1);
System.out.println(matcher.find());
//2)返回true
matcher = pattern.matcher(test2);
System.out.println(matcher.find());
//3)返回true
matcher = pattern.matcher(test3);
System.out.println(matcher.find(2));
//4)返回false
matcher = pattern.matcher(test3);
System.out.println(matcher.find(5));

你可能感兴趣的:(后端—开发语言—Java,java,开发语言)