5、正则表达式的陷阱
public class StringSplit {
public static void main(String[] args) {
String str = "java.is.funny.hello.world";
String[] strArr = str.split(".");
for ( String s : strArr ) {
System.out.println(s);
}
}
}
上面本希望通过调用String提供的split()方法,以点号(.)作为分隔符来分割这个字符串,但运行该程序时发现没有任何输出内容。
对于上面程序的运行结果,要注意如下两点。
- String提供的split(String regex)方法需要的参数是正则表达式。
- 正则表达式中的点号(.)可匹配任意字符。
public class StringSplit {
public static void main(String[] args) {
String str = "java.is.funny.hello.world";
String[] strArr = str.split("\\.");
for ( String s : strArr ) {
System.out.println(s);
}
}
}
输出结果为:
java
is
funny
hello
world
is
funny
hello
world
从JDK1.4开始,Java加入了对正则表达式的支持,String类也增加了一些方法用于支持正则表达式,具体有如下方法。
matches(String regex):判断该字符串是否匹配指定的正则表达式。
String replaceAll(String regex , String replacement):将字符串中所有匹配指定的正则表达式的子串替换成replacement后返回。
String replaceFirst(String regex , String replacement):将字符串中第一个匹配指定的正则表达式的子串替换成replacement后返回。
String[] split(String regex):以regex正则表达式的子串作为分隔符来分割该字符串。
以上四个方法都需要regex参数,这个参数就是正则表达式,因此使用这些方法时要特别小心。String提供了一个与replaceAll()功能相当的方法,如下所示:
replace(CharSequence target , CharSequence replacement):将字符串中所有的target子串替换成replacement后返回。
public class StringReplace {
public static void main(String[] args) {
String str = "java.is.funny.hello.world";
String path1 = str.replace(".", "\\"); //使用replace()方法
System.out.println(path1);
String path2 = str.replaceAll("\\.", "\\\\");
System.out.println(path2);
}
}
输出结果为:
java\is\funny\hello\world
java\is\funny\hello\world
java\is\funny\hello\world