0%

Java正则

前言:使用java正则表达式来处理字符串

导入

1
2
import java.util.regex.Matcher;
import java.util.regex.Pattern;

Pattern与Matcher一起合作.Matcher类提供了对正则表达式的分组支持,以及对正则表达式的多次匹配支持. 单独用Pattern只能使用Pattern.matches(String regex,CharSequence input)一种最基础最简单的匹配

Pattern

Pattern类用于创建一个正则表达式,它的构造方法是私有的,不可以直接创建,一般通过Pattern.complie(String regex)创建正则表达式,

1
2
3
Pattern p = Pattern.compile("_[a-z]");
// pattern()返回正则表达式的字符串形式
System.out.println(p.pattern());

Boolean Pattern.matches(String regex,CharSequence input)是一个静态方法,用于快速匹配字符串,该方法适合用于只匹配一次,且匹配全部字符串,返回布尔值

1
2
3
4
5
Pattern p = Pattern.compile("_[a-z]");
// 输出:true
System.out.println(Pattern.matches("_[a-z]","_a"));
// 输出:false
System.out.println(Pattern.matches("_[a-z]","__a"));

Matcher

Pattern.matcher(CharSequence input)返回一个Matcher对象

Matcher类的构造方法也是私有的,不能随意创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例

Pattern类只能做一些简单的匹配操作,要想得到更强更便捷的正则匹配操作,那就需要将Pattern与Matcher一起合作.Matcher类提供了对正则表达式的分组支持,以及对正则表达式的多次匹配支持.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Pattern p = Pattern.compile("_[a-z]");
Matcher m = p.matcher("user_id");
// matches()对整个字符串进行匹配,只有整个字符串都匹配了才返回true
System.out.println("m.matches(): " + m.matches());

// lookingAt()对前面的字符串进行匹配,只有匹配到的字符串在最前面才返回true
System.out.println("m.lookingAt(): " + m.lookingAt());

// find()对字符串进行匹配,匹配到的字符串可以在任何位置
System.out.println("m.find(): " + m.find());


// 返回匹配到的子字符串在字符串中的索引位置
System.out.println("m.start(): " + m.start());

// 返回匹配到的子字符串的最后一个字符在字符串中的索引位置.
System.out.println("m.end(): " + m.end());

// 返回匹配到的子字符串
System.out.println("m.group(): " + m.group());

image-20200101225809391

-------------本文结束感谢您的阅读-------------