如何在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 婆婆高寿祝福语大全简短