如何在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 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短