java正则表达式学习笔记(四)

  接着学习java.util.regex包里关于正则表达式的包,因为string类只提供部分正则表达式的功能,不能充

分展现正则表达式强大的功能.
  java.util.regex包里有两个类,一个接口,一个异常,正则表达式的主要功能都是在Pattern,Matcher两个

类里实现了,现在先学习Pattern类,Pattern类一共有8个方法和两个方法的重载,还有8个字段,下面直接看

一个例子你就明白他的原理,如果不明白可以查看JDK的帮助.

import java.util.regex.Pattern;
import java.util.regex.Matcher;
//compile(),split(),flags(),matcher(),matches(),quote(),toString(),pattern()
class PatternTest{
public static void main(String[] args){
String regex
= "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+[.]((net)|(com)|(com.cn)|(cn))$";
Pattern p
= Pattern.compile(regex);
String result
= p.pattern();
p(result);
p(p.flags());
result
= p.toString();
p(result);

String regex1
= "mx";
Pattern p1
= Pattern.compile(regex1);
Matcher m1
= p1.matcher("abcdefgABCDEFG");
while(m1.find()){
p(m1.group());
//abc
}
Pattern p2
= Pattern.compile(regex1,Pattern.CASE_INSENSITIVE);
Matcher m2
= p2.matcher("abcdefgABCDEFG");
while(m2.find()){
p(m2.group());
//abc ABC
}

p(p2.flags());

boolean b ;
b
= Pattern.matches(regex,"lovefeel2004@126.com");
p(b);

p(Pattern.quote(
"lovefeel2004@126.com"));

Pattern p3
= Pattern.compile("@");
String[] result1
= p3.split("love@feel@2004@com@cn");
for(String s: result1){
p(s);
}

result1
= p3.split("love@feel@2004@com@cn",3);
for(String s: result1){
p(s);
}
}

public static void p(Object o){
System.out.println(o);
}
}

运行结果:

posted @ 2008-10-28 12:33  幽梦新影  阅读(959)  评论(1编辑  收藏  举报