如何在Java中执行正则表达式?

这个例子演示了我们如何用Java做正则表达式。正则表达式类在java.uti.regex包中。主要阶级包括java.util.regex.Pattern阶级和java.util.regex.Matcher阶级。

在此示例中,我们仅测试以下字符串中是否存在字符串文字,我们将搜索单词“ lazy”。

package org.nhooo.example.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo {
    public static void main(String[] args) {
        /*
         * To create a Pattern instance we must call the static method
         * called compile() in the Pattern class. Pattern object is
         * the compiled representation of a regular expression.
         */
        Pattern pattern = Pattern.compile("lazy");

        /*
         * The Matcher class also doesn't have the public constructor
         * so to create a matcher call the Pattern's class matcher()
         * method. The Matcher object it self is the engine that match
         * the input string against the provided pattern.
         */
        String input = "The quick brown fox jumps over the lazy dog";
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            System.out.format("Text \"%s\" found at %d to %d.%n",
                matcher.group(), matcher.start(), matcher.end());
        }
    }
}

上面的代码片段的输出是:

Text "lazy" found at 35 to 39.