正则表达式 jakarta-oro
jakarta-oro 正则表达式库是最全面的正则表达式API之一,而且它与Perl 5正则表达式完全兼容。另外,它也是优化得最好的API之一。
下面程序简单介绍了jakarta-oro 的关键对象:PatternCompiler,Pattern,PatternMatcher
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;
public class JoroTest {
public static void main(String[] args) {
String str = "172.20.16.2 - - " +
"[02/02/2007:10:30 \"GET " +
"/IsAlive.htm HTTP/1.0\"]";
String regexp = "([0-9]{1,3}\\.[0-9]{1,3}" +
"\\.[0-9]{1,3}\\.[0-9]{1,3})" +
"\\s-\\s-\\s(\\[[^\\]]+\\])";
echo("regexp : " + regexp);
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = null;
try{
pattern = compiler.compile(regexp);
PatternMatcher matcher = new Perl5Matcher();
if(matcher.contains(str, pattern)){
MatchResult result = matcher.getMatch();
echo(result.group(1));
echo(result.group(2));
}
}catch(Exception e){
e.printStackTrace();
}
}
public static void echo(String str){
System.out.println(str);
}
}
在Java中,必须对每一个向前的斜杠(“\”)进行转义处理,这样表达式不太容易看,所以应该小心谨慎,我们可以首先输入未经转义处理的正则表达式,然后从左到右依次把每一个“\”替换成“\\”,如果有问题可以输出到控制台来检查。
irini
2007-05-20 19:23:17
评论:0
阅读:230
引用:0
