如何在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 红包祝福语简短10字
18 周六早晨祝福语简短