在 java .util. regex 包中主要包括三类,其中的Matcher对象是解释和匹配输入字符串的对象,今天小编将为大家带来Matcher类的方法。
一、Matcher类的方法
Matcher类没有通用的构造方法,需要调用Pattern对象的Matcher方法来获得Matcher对象。
1、 索引 方法
索引方法提供了一个有用的索引值,以准确地指示在输入字符串中可以找到匹配项的位置:
方法 | 说明 |
public int start() | 返回之前匹配项的初始索引。 |
public int start(int group) | 返回给定组在之前匹配操作中捕获的子序列的初始索引 |
public int end() | 返回最后一个匹配字符后的偏移量。 |
public int end(int group) | 返回给定组在之前匹配操作中捕获的子序列的最后一个字符之后的偏移量。 |
2、查找方法
查找方法检查输入字符串并返回一个布尔值,以指示是否找到该模式:
方法 | 说明 |
public boolean lookingAt() | 尝试将模式与从区域开始的输入序列相匹配。 |
public boolean find() | 尝试查找与模式匹配的输入序列的下一个子序列。 |
public boolean find(int start) | 重置匹配器,然后从指定的索引开始,尝试查找与模式匹配的输入序列的下一个子序列。 |
public boolean matches() | 尝试将整个区域与模式匹配。 |
3、替换方法
替换方法是替换输入字符串中的文本:
方法 | 说明 |
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 quote replace ment(String s) | 返回指定字符串的文字替换字符串。这个方法返回一个字符串,就像传递给matcher类的appendreplacement方法的文本字符串一样。 |
4、start和end方法
下面是一个计算单词“cat”在输入字符串中出现次数的示例:
运行结果:
可以看到,这个示例使用单词边界来确保字母“C”、“a”、“t”不仅仅是一个长单词的字符串。它还提供了一些有关匹配在输入字符串中发生的位置的有用信息。
start方法返回给定组在上一次匹配操作中捕获的子序列的初始索引,end方法将最后一个匹配字符的索引加1。
5、matches和lookingAt方法
matches和lookingAt方法都用于尝试匹配输入序列模式。不同之处在于匹配需要匹配整个序列,而lookingAt则不需要。
虽然lookingAt方法不需要匹配整个句子,但它需要从第一个字符开始匹配。
这两种方法通常用于输入字符串的开头。
示例:
运行结果:
6、replaceFirst和replaceAll方法
replaceFirst和replaceAll方法用于替换与正则表达式匹配的文本。不同之处在于replaceFirst替换第一个匹配项,replaceAll替换所有匹配项。
示例:
运行结果:
7、 append Replacement和appendTail方法
matcher类还提供用于文本替换的appendReplacement和appendTail方法。
示例:
运行结果:
二、PatternSyntaxException 类的方法
PatternSyntaxException是一个非强制的异常类,它指示正则表达式模式中的语法错误。
PatternSyntaxException类提供了以下方法来帮助我们查看出了什么问题。
方法 | 说明 |
public String getDescription() | 获取错误的描述。 |
public int getIndex() | 获取错误的索引。 |
public String getPattern() | 获取错误的正则表达式模式。 |
public String getMessage() | 返回一个多行字符串,其中包含语法错误及其索引的描述、错误的正则表达式模式以及模式中错误索引的可视指示。 |
以上就是关于大数据编程入门:Java Matcher类的方法全部内容了,希望这篇文章能够帮助到大家~
Reliable write ups. Kudos.
analysis data for dissertation research proposal for phd application
Many thanks! Plenty of forum posts.
online casino canada real money online casino gambling site
Many thanks! I like it!
buy your essays
Many thanks. A good amount of information!
can someone write a check for me write essay for you
You actually mentioned that well.
paid essay writer professional essay writer
Kudos. Great information!
university essay writer hire someone to write a book for me
Kudos! Quite a lot of write ups.
writes essays for you write my essays for me
You actually suggested that terrifically.
help me write a cover letter for a job essay writers for hire