您的位置:首页 > 其它

欢迎使用CSDN-markdown编辑器

2017-03-21 10:24 281 查看
String类中字符串替换操作出现的问题

当我们编写程序如下:采用replaceAll()替换掉Helloworld中字母H时,执行结果正确。

class StringDemo

{

public static void main(String[] args)

{

String str1=”Helloworld”;

System.out.println(str1.replaceAll(“H”,”A”));

}

}

然而我们仍采用此方法将*Helloworld中字符换成A时,编译时会报错。

class StringDemo

{

public static void main(String[] args)

{

String str1=”**Helloworld”;

System.out.println(str1.replaceAll(“*”,”A”));

}

}

java.util.regex.PatternSyntaxException: Dangling meta character ‘*’ near index 0

这因为因为String的relaceAll以正则表达式分词,*为正则表达式的特殊字符、故而抛出异常.

解决办法:

,+、*、|、\等符号为正则表达示特殊字符。

只需要加[]、或是\即可。

例如:

class StringDemo

{

public static void main(String[] args)

{

String str1=”**Helloworld”;

System.out.println(str1.replaceAll(“\*”,”A”));

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: