英文:
replaceAll method in java
问题
我在我的Java应用程序中使用replaceAll方法遇到了问题。
我认为存在编译错误,代码如下:
public static void main(String[] args) {
String Str = " Welcome to Itpro.com please visit programming.itpro.com";
System.out.println(Str.replaceAll(".com", ".net"));
}
输出结果为:
We.nete to Itpro.net please visit programming.itpro.net
欢迎词已更改为`we.nete`,这是不正确的。
当我将欢迎词中的小写c更改为大写C时,一切正常。
我不知道该怎么办。
英文:
I have a problem about using replaceAll method in my java app.
I think there is a compile error, and the code is:
public static void main(String[] args) {
String Str = " Welcome to Itpro.com please visit programming.itpro.com";
System.out.println(Str.replaceAll(".com", ".net"));
}
and output is:
We.nete to Itpro.net please visit programming.itpro.net
welcome word has changed to we.nete
and this is not correct.
When I change c letter in welcome word to capital C in str, everything is ok
I dont know what i do.
答案1
得分: 0
第一个传递给String#replaceAll()
的参数将被解释为正则表达式模式。由于字符.
表示任何单个字母,因此.com
也会匹配到Welcome
。要获得您想要的行为,您需要使用反斜杠来转义点:
String str = "Welcome to Itpro.com please visit programming.itpro.com";
System.out.println(str.replaceAll("\\.com", ".net"));
英文:
The first parameter passed to String#replaceAll()
will be interpreted as a regular expression pattern. As the character .
means any single letter, therefore .com
will also match to Welcome
. To get the behavior you want, you need to escape the dot with backslash:
<!-- language: java -->
String str = "Welcome to Itpro.com please visit programming.itpro.com";
System.out.println(str.replaceAll("\\.com", ".net"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论