javaAPI:
public static void main(String[] args) {
String str = "lixin_2002@163.com";
String reg = "([a-zA-Z0-9]+)\\@[a-zA-Z0-9]+\\.[a-zA-Z0-9]+$";
Pattern p = Pattern.compile(reg);
Matcher m = p.matcher(str);
System.out.println(m.find());
}
jakarta-oro的使用1(简单匹配):
public static void main(String[] args) throws MalformedPatternException {
//取出日志文件的IP和时间
String log = "172.26.155.241 - - [26/Feb/2001:10:56:03 -0500]";
String logreg = "(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})\\s-\\s-\\s\\[([^\\]]+)\\]";
PatternCompiler pc = new Perl5Compiler();
org.apache.oro.text.regex.Pattern p = pc.compile(logreg);
PatternMatcher pm = new Perl5Matcher();
System.out.println(pm.contains(str,p));
if(pm.contains(log,p)){
org.apache.oro.text.regex.MatchResult mr = pm.getMatch();
System.out.println("ip: " + mr.group(1));
System.out.println("time: " + mr.group(2));
}
}
jakarta-oro的使用2(匹配多个):
public static void main(String[] args) throws MalformedPatternException {
//取出HTML标签里的属性值及值 分两次
String html = "<font face='Arial, Serif' size='12' color='red'>";
String reg1 = "<[a-z]+\\s+(.+)>";
String reg2 = "([a-z]+)='([^']+)'";
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = compiler.compile(reg1);
PatternMatcher matcher = new Perl5Matcher();
System.out.println(matcher.contains(html, pattern));
if(matcher.contains(html, pattern)){
MatchResult result = matcher.getMatch();
String arrs = result.group(1); //先取出属性列表
System.out.println(arrs);
Pattern pattern2 = compiler.compile(reg2);
PatternMatcherInput input = new PatternMatcherInput(arrs);
while(matcher.contains(input, pattern2)){
result = matcher.getMatch();
System.out.println(result.group(1)+"=" + result.group(2));
}
}
}
jakarta-oro的使用3(字符串替换):
public static void main(String[] args) throws MalformedPatternException {
//将str1和str2 的前面aaa部分替换成www 而后面的不替换
String str = "aaa&abc";
String str2 = "aaa&cde";
String reg = "aaa&(.+)";
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = compiler.compile(reg,Perl5Compiler.CASE_INSENSITIVE_MASK);
PatternMatcher matcher = new Perl5Matcher();
String result = Util.substitute(matcher, pattern,
new Perl5Substitution("www&$1"), //注意:$1 $2等 表示已经匹配且提取出来的组
str,Util.SUBSTITUTE_ALL);
System.out.println(result);
}