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

在(一)和(二)中只是了解了一下正则表达式,今天深入了学习正则表达式在string类的应用,主要在matches(),split(),replace(),replaceAll(),replaceFirst等方法的应用.

现在先看看它们在JDK1.6中的定义:
matches
  public boolean matches(String regex)

  告知此字符串是否匹配给定的正则表达式。 

replace
  public String replace(char oldChar,char newChar)

  返回一个新的字符串,它是通过用 newChar 替换此字符串中出

split
  public String[] split(String regex,int limit)

  根据匹配给定的正则表达式来拆分此字符串。
  public String[] split(String regex)

  根据给定正则表达式的匹配拆分此字符串.该方法的作用就像是使用给定的表达式和限制参数 0 来调用两参数 split 方法。因此,所得数组中不包括结尾空字符串。

replaceAll
  public String replaceAll(String regex,String replacement)

  使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
replaceFirst
  public String replaceFirst(String regex,String replacement)

  使用给定的 replacement 替换此字符串匹配给定的正则表达式的第一个子字符串。

关于以上方法的详细信息可以到JDK中查阅,在这里就不多说了,下面用一个例子来说明以上这些方法怎么样用的.

public class TestRegex{
public static void main(String[] args){
String str
= "lovefeel2004@126.com";
//matches()的用法
String regex1 = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+[.]((net)|(com)|(com.cn))$";
boolean b ;
b
= str.matches(regex1);
p(b
+"\n");

//spilt()的用法
String[] split1 = str.split("@");
p(
"用@去分割str得到的字符串:");
for(String s : split1){
p(s
+" ");
}

String[] split2
= str.split("@|\\.");
p(
"\n用@或.去分割str得到的字符串:");
for(String s : split2){
p(s
+" ");
}
//replace(),replaceAll(),replaceFirst()的用法
p("\n用#去代替@后的str:");
p(str.replace(
"@","#") + "\n");
p(
"用d去代替o后的str:");
p(str.replaceAll(
"o","d") + "\n");
p(
"用d代替第一个o后的str:");
p(str.replaceFirst(
"o","d") + "\n");

}
//打印方法
public static void p(Object o){
System.out.print(o);
}
}

结果:

接下来再学习java.util.regex包的类,毕竟String只提供简单的正则表达式功能.

 

本文如有不正确,请大家指正!!!

posted @ 2008-10-27 15:55  幽梦新影  阅读(3808)  评论(0编辑  收藏  举报