欢迎使用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”));
}
}
当我们编写程序如下:采用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”));
}
}
相关文章推荐
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器ss
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器
- 欢迎使用CSDN-markdown编辑器