如何在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.
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短