Java正则表达式系列--Pattern和Matcher的使用

原文网址:Java正则表达式系列--Pattern和Matcher的使用_IT利刃出鞘的博客-CSDN博客

简介

说明

本文介绍Java的正则表达式中的两个重要类的用法:Pattern和Matcher。

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

  1. Pattern:通过正则表达式后创建一个匹配模式。
  2. Matcher:使用Pattern实例提供的正则表达式对目标字符串进行匹配。

示例

// 将正则表达式编译成 Pattern 对象,(1 或 0 个符号,后跟 至少一个数组[0-9])
Pattern pattern = Pattern.compile("-?\\d+");

// 利用 Pattern 对象生成 Matcher 对象.
Matcher matcher = pattern.matcher("-1234");

// 查看匹配结果
System.out.println(matcher.matches());

上述也可以这么写(如果只用一次正则表达式可使用Pattern的静态方法matches):

// 使用 Pattern 对象的静态方法执行一次正则匹配.
System.out.println(Pattern.matches("-?\\d+", "123"));

也可以这么写:

"123".matches("-?\\d+");

Pattern

创建

下边两个静态方法可以创建Pattern

public static Pattern compile(String regex)
public static Pattern compile(String regex, int flags) 

示例: 

Pattern pattern = Pattern.compile("[a-z]\\d{3}.*");

分割

该方法用于分割字符串,并返回一个String[]

//通过正则表达式对input进行分割。
public String[] split(CharSequence input)

//通过正则表达式对input进行分割,limit参数指明分割的段数。
public String[] split(CharSequence input, int limit)

示例

Pattern p=Pattern.compile("\\d+"); 
String[] str=p.split("我的QQ是:456456我的电话是:0532214我的邮箱是:[email protected]"); 

结果

str[0]="我的QQ是:", str[1]="我的电话是:", str[2]="我的邮箱是:[email protected]"

其他

创建Matcher变量

public Matcher matcher(CharSequence input) 为目标字符串input创建一个Matcher对象。

将字符串s转换为正则字面量

public static String quote(String s)

Matcher

索引方法

索引方法提供了有用的索引值,精确表明输入字符串中在哪能找到匹配:

方法

说明

public int start()

返回以前匹配的初始索引。

public int start(int group)

返回在以前的匹配操作期间,由给定组所捕获的子序列的初始索引

public int end()

返回最后匹配字符之后的偏移量。

public int end(int group)

返回在以前的匹配操作期间,由给定组所捕获子序列的最后字符之后的偏移量。

查找方法

查找方法用来检查输入字符串并返回一个布尔值,表示是否找到该模式:

方法

说明

public boolean lookingAt()

尝试将从区域开头开始的输入序列与该模式匹配。

public boolean find()

尝试查找与该模式匹配的输入序列的下一个子序列。

public boolean find(int start)

重置此匹配器,然后尝试查找匹配该模式、从指定索引开始的输入序列的下一个子序列。

public boolean matches()

尝试将整个区域与模式匹配。

替换方法

替换方法是替换输入字符串里文本的方法:

方法

说明

public Matcher appendReplacement(

        StringBuffer sb, String replacement)

实现非终端添加和替换步骤。

public StringBuffer appendTail(StringBuffer sb)

实现终端添加和替换步骤。

public String replaceAll(String replacement)

替换模式与给定替换字符串相匹配的输入序列的每个子序列。

public String replaceFirst(String replacement)

替换模式与给定替换字符串匹配的输入序列的第一个子序列。

public static String quoteReplacement(String s)

返回指定字符串的字面替换字符串。这个方法返回一个字符串,就像传递给Matcher类的appendReplacement 方法一个字面字符串一样工作。

猜你喜欢

转载自blog.csdn.net/feiying0canglang/article/details/128194173