星期日, 十一月 26, 2006

用java处理正则表达式的例子

调用Jakarta ORO, 要先下载ORO库http://jakarta.apache.org/oro/

PatternCompiler compiler = new Perl5Compiler();
PatternMatcher matcher = new Perl5Matcher();
MatchResult result;
Pattern pattern;
PatternMatcherInput input;

String text = "t[012]n"; //正则表达式
String searchedText="fsdafsafdt1nfsdfs"; //待匹配的字符串

System.out.print("Compiling regular expression.\n");

try {
pattern = compiler.compile(text, Perl5Compiler.CASE_INSENSITIVE_MASK);
} catch (MalformedPatternException e) {
System.out.print("\nMalformed Regular Expression:\n"
+ e.getMessage());
return;
}

int matchNum = 0;

System.out.print("\nSearching\n\n");

input = new PatternMatcherInput(searchedText);

while (matcher.contains(input, pattern)) {
int groups;

result = matcher.getMatch();
++matchNum;

System.out.print("Match " + matchNum + ": " + result.group(0)
+ "\n");
groups = result.groups();

if (groups > 1) {
System.out.print(" Subgroups:\n");
for (int group = 1; group < groups; group++) {
System.out.print(" " + group + ": "
+ result.group(group) + "\n");
}
}
}

System.out.print("\nThe input contained " + matchNum + " matches.");

没有评论: