Java中正则表达式相关类Pattern和Matcher的使用

在Java中,java.util.regex包定义了正则表达式使用到的相关类,其中最主要的两个类为:Pattern、Matcher:

 

Pattern 编译正则表达式创建一个匹配模式;

 

Matcher 使用Pattern实例提供的正则表达式对目标字符串进行匹配,是真正影响搜索的对象。。

 

1、Pattern类常用方法

public static Pattern compile(String regex)

public static Pattern compile(String regexint flags)

public String pattern()

public Matcher matcher(CharSequence input)

Pattern的构造方法是私有的,不可以直接创建,通过静态方法compile创建Pattern对象,查看源代码发现compile直接调用了Pattern构造函数

2、Matche类常用方法

匹配方法:public boolean matches() / lookingAt() / find()

返回索引和偏移量:public int start() / end() 

返回匹配字符串:public String group()

public int start(int) / end(int) 

public String group(int)

替换:public String replaceAll(String replacement) / replaceFirst(String replacement)

猜你喜欢

转载自blog.csdn.net/weixin_42658949/article/details/81501730