Documentation

The Java™ Tutorials
Hide TOC
Methods of the Matcher ClassMatcher类的方法
Trail: Essential Java Classes
Lesson: Regular Expressions

Methods of the Matcher ClassMatcher类的方法

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索引方法

Index methods provide useful index values that show precisely where the match was found in the input string:索引方法提供有用的索引值,精确显示在输入字符串中找到匹配项的位置:

Study Methods研究方法

Study methods review the input string and return a boolean indicating whether or not the pattern is found.研究方法检查输入字符串并返回一个布尔值,指示是否找到该模式。

Replacement Methods替代方法

Replacement methods are useful methods for replacing text in an input string.替换方法是替换输入字符串中文本的有用方法。

Using the start and end Methods使用start方法和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" are not merely a substring in a longer word. 您可以看到,此示例使用单词边界来确保字母“d”、“o”、“g”不仅仅是较长单词中的子字符串。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返回最后一个匹配字符的索引加上一个。

Using the matches and lookingAt Methods使用matcheslookingAt方法

The matches and lookingAt methods both attempt to match an input sequence against a pattern. matcheslookingAt方法都试图根据模式匹配输入序列。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

Using replaceFirst(String) and replaceAll(String)使用replaceFirst(String)replaceAll(String)

The replaceFirst and replaceAll methods replace text that matches a given regular expression. replaceFirstreplaceAll方法替换与给定正则表达式匹配的文本。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都替换为catBut 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 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-."此方法的API声明“给定正则表达式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而不是replaceAllIt accepts the same parameter.它接受相同的参数。

Using appendReplacement(StringBuffer,String) and appendTail(StringBuffer)使用appendReplacement(StringBuffer,String)appendTail(StringBuffer)

The Matcher class also provides appendReplacement and appendTail methods for text replacement. Matcher类还提供用于文本替换的appendReplacementappendTail方法。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-

Matcher Method Equivalents in java.lang.Stringjava.lang.String中的Matcher方法等价物

For convenience, the String class mimics a couple of Matcher methods as well:为方便起见,String类还模拟了两个Matcher方法:


Previous page: Methods of the Pattern Class
Next page: Methods of the PatternSyntaxException Class