replaceAll方法在Java中是用于替换字符串中的所有匹配项的方法。

huangapple go评论44阅读模式
英文:

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 = &quot;Welcome to Itpro.com please visit programming.itpro.com&quot;;
System.out.println(str.replaceAll(&quot;\\.com&quot;, &quot;.net&quot;));

huangapple
  • 本文由 发表于 2023年2月19日 22:07:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500685.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定