The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
This section describes some additional useful methods of the 本节介绍Matcher
class. Matcher
类的一些其他有用方法。For convenience, the methods listed below are grouped according to functionality.为方便起见,下面列出的方法根据功能进行分组。
Index methods provide useful index values that show precisely where the match was found in the input string:索引方法提供有用的索引值,精确显示在输入字符串中找到匹配项的位置:
public int start()
public int start(int group)
public int end()
public int end(int group)
Study methods review the input string and return a boolean indicating whether or not the pattern is found.研究方法检查输入字符串并返回一个布尔值,指示是否找到该模式。
public boolean lookingAt()
public boolean find()
public boolean find(int start)
public boolean matches()
Replacement methods are useful methods for replacing text in an input string.替换方法是替换输入字符串中文本的有用方法。
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)
String
for the specified String
. String
的文字替换String
。String
that will work as a literal replacement s
in the appendReplacement
method of the Matcher
class. String
,该字符串将作为Matcher
类的appendReplacement
方法中的字面量替换s
。String
produced will match the sequence of characters in s
treated as a literal sequence. String
将匹配s
中作为文字序列处理的字符序列。'\'
) and dollar signs ('$'
) will be given no special meaning.\
)和美元符号($
)没有特殊意义。start
and end
Methodsstart
方法和end
方法Here's an example, 下面是一个示例MatcherDemo.java
, that counts the number of times the word "dog" appears in the input string.MatcherDemo.java
,它统计单词“dog”在输入字符串中出现的次数。
import java.util.regex.Pattern; import java.util.regex.Matcher; public class MatcherDemo { private static final String REGEX = "\\bdog\\b"; private static final String INPUT = "dog dog dog doggie dogg"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); // get a matcher object Matcher m = p.matcher(INPUT); int count = 0; while(m.find()) { count++; System.out.println("Match number " + count); System.out.println("start(): " + m.start()); System.out.println("end(): " + m.end()); } } }
OUTPUT: Match number 1 start(): 0 end(): 3 Match number 2 start(): 4 end(): 7 Match number 3 start(): 8 end(): 11
You can see that this example uses word boundaries to ensure that the letters 您可以看到,此示例使用单词边界来确保字母“d”、“o”、“g”不仅仅是较长单词中的子字符串。"d" "o" "g"
are not merely a substring in a longer word. It also gives some useful information about where in the input string the match has occurred. 它还提供了一些有用的信息,说明在输入字符串中匹配发生的位置。The start
method returns the start index of the subsequence captured by the given group during the previous match operation, and end
returns the index of the last character matched, plus one.start
方法返回给定组在上一次匹配操作中捕获的子序列的开始索引,end
返回最后一个匹配字符的索引加上一个。
matches
and lookingAt
Methodsmatches
和lookingAt
方法The matches
and lookingAt
methods both attempt to match an input sequence against a pattern. matches
和lookingAt
方法都试图根据模式匹配输入序列。The difference, however, is that 然而,不同之处在于matches
requires the entire input sequence to be matched, while lookingAt
does not. matches
需要匹配整个输入序列,而lookingAt
则不需要。Both methods always start at the beginning of the input string. 这两种方法总是从输入字符串的开头开始。Here's the full code, 下面是完整的代码MatchesLooking.java
:MatchesLooking.java
:
import java.util.regex.Pattern; import java.util.regex.Matcher; public class MatchesLooking { private static final String REGEX = "foo"; private static final String INPUT = "fooooooooooooooooo"; private static Pattern pattern; private static Matcher matcher; public static void main(String[] args) { // Initialize pattern = Pattern.compile(REGEX); matcher = pattern.matcher(INPUT); System.out.println("Current REGEX is: " + REGEX); System.out.println("Current INPUT is: " + INPUT); System.out.println("lookingAt(): " + matcher.lookingAt()); System.out.println("matches(): " + matcher.matches()); } }
Current REGEX is: foo Current INPUT is: fooooooooooooooooo lookingAt(): true matches(): false
replaceFirst(String)
and replaceAll(String)
replaceFirst(String)
和replaceAll(String)
The replaceFirst
and replaceAll
methods replace text that matches a given regular expression. replaceFirst
和replaceAll
方法替换与给定正则表达式匹配的文本。As their names indicate, 如其名称所示,replaceFirst
replaces the first occurrence, and replaceAll
replaces all occurrences. replaceFirst
替换第一个引用,replaceAll
替换所有引用。Here's the 以下是ReplaceDemo.java
code:ReplaceDemo.java
代码:
import java.util.regex.Pattern; import java.util.regex.Matcher; public class ReplaceDemo { private static String REGEX = "dog"; private static String INPUT = "The dog says meow. All dogs say meow."; private static String REPLACE = "cat"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); // get a matcher object Matcher m = p.matcher(INPUT); INPUT = m.replaceAll(REPLACE); System.out.println(INPUT); } }
OUTPUT: The cat says meow. All cats say meow.
In this first version, all occurrences of 在第一个版本中,所有出现的dog
are replaced with cat
. dog
都替换为cat
。But why stop here? 但是为什么停在这里?Rather than replace a simple literal like 您可以替换匹配任何正则表达式的文本,而不是替换像dog
, you can replace text that matches any regular expression. dog
这样的简单文本。The API for this method states that "given the regular expression 此方法的API声明“给定正则表达式a*b
, the input aabfooaabfooabfoob
, and the replacement string -
, an invocation of this method on a matcher for that expression would yield the string -foo-foo-foo-
."a*b
、输入aabfooaabfooabfoob
和替换字符串-
,在该表达式的匹配器上调用此方法将生成字符串-foo-foo-foo-
。”
Here's the 以下是ReplaceDemo2.java
code:ReplaceDemo2.java
代码:
import java.util.regex.Pattern; import java.util.regex.Matcher; public class ReplaceDemo2 { private static String REGEX = "a*b"; private static String INPUT = "aabfooaabfooabfoob"; private static String REPLACE = "-"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); // get a matcher object Matcher m = p.matcher(INPUT); INPUT = m.replaceAll(REPLACE); System.out.println(INPUT); } }
OUTPUT: -foo-foo-foo-
To replace only the first occurrence of the pattern, simply call 要仅替换模式的第一个匹配项,只需调用replaceFirst
instead of replaceAll
. replaceFirst
而不是replaceAll
。It accepts the same parameter.它接受相同的参数。
appendReplacement(StringBuffer,String)
and appendTail(StringBuffer)
appendReplacement(StringBuffer,String)
和appendTail(StringBuffer)
The Matcher
class also provides appendReplacement
and appendTail
methods for text replacement. Matcher
类还提供用于文本替换的appendReplacement
和appendTail
方法。The following example, 下面的示例RegexDemo.java
, uses these two methods to achieve the same effect as replaceAll
.RegexDemo.java
使用这两种方法实现与replaceAll
相同的效果。
import java.util.regex.Pattern; import java.util.regex.Matcher; public class RegexDemo { private static String REGEX = "a*b"; private static String INPUT = "aabfooaabfooabfoob"; private static String REPLACE = "-"; public static void main(String[] args) { Pattern p = Pattern.compile(REGEX); Matcher m = p.matcher(INPUT); // get a matcher object StringBuffer sb = new StringBuffer(); while(m.find()){ m.appendReplacement(sb,REPLACE); } m.appendTail(sb); System.out.println(sb.toString()); } }
OUTPUT: -foo-foo-foo-
java.lang.String
java.lang.String
中的Matcher方法等价物For convenience, the 为方便起见,String
class mimics a couple of Matcher
methods as well:String
类还模拟了两个Matcher
方法:
public String replaceFirst(String regex, String replacement)
str.replaceFirst(regex, repl)
yields exactly the same result as the expression Pattern.compile(regex).matcher(str).replaceFirst(repl)
str.replaceFirst(regex, repl)
形式的此方法会产生与表达式Pattern.compile(regex).matcher(str).replaceFirst(repl)
完全相同的结果public String replaceAll(String regex, String replacement)
str.replaceAll(regex, repl)
yields exactly the same result as the expression Pattern.compile(regex).matcher(str).replaceAll(repl)
str.replaceAll(regex, repl)
形式会产生与表达式Pattern.compile(regex).matcher(str).replaceAll(repl)
完全相同的结果