简体   繁体   English

String replaceAll方法(Java)

[英]String replaceAll method (Java)

I have following problem, 我有以下问题,

Code: 码:

String a="Yeahh, I have no a idea what's happening now!";
System.out.println(a);
a=a.replaceAll("a", "");
System.out.println(a);

Before removing 'a', result: 在删除'a'之前,结果如下:

Yeahh, I have no a idea what's happening now! 是的,我不知道现在发生了什么!

Actual Result: After removing 'a', result: 实际结果:删除'a'后,结果:

Yehh, I hve no ide wht's hppening now! 是的,我现在没有想法了!

Desired Result: 期望的结果:

Yeahh, I have no idea what's happening now! 是的,我不知道现在发生了什么!

Anyone can give me some advices to achieve my desired result? 有人可以给我一些建议来达到我想要的结果吗?

a = a.replace(" a ", " ");

You don't need the replaceAll(..) method - it is if you want to use regex, and you don't need it, at least for this example. 您不需要replaceAll(..)方法 - 如果您想使用正则表达式,并且您不需要它,至少对于此示例。

If you need this for more complex examples than shown, then use replaceAll(..) and take a look at java.util.regex.Pattern . 如果您需要更复杂的示例而不是显示,请使用replaceAll(..)并查看java.util.regex.Pattern For example, matching all whitespace characters is done using \\s 例如,匹配所有空白字符是使用\\s完成\\s

你应该确定要删除的特定“a”试试这个a.replace(" a ", " ");

You were asking to replace every 'a', and that is what you got. 你要求更换每一个'a',这就是你得到的。

Some solutions: 一些解决方案

  • replaceAll(" a ", " ") (note the spaces around the 'a') replaceAll(“a”,“”)(注意'a'周围的空格)
  • use regex to chek for 'a' surrounded by word barriers (\\b if I'm not mistaken) 使用正则表达式来搜索被字障碍包围的'a'(\\ b,如果我没有记错的话)

Try using this: 试试这个:

String str = "Yeahh, I have no a idea what's happening now!"; String str =“是的,我不知道现在发生了什么!”;

String newStr = str.replaceAll(" a ", " "); String newStr = str.replaceAll(“a”,“”);

a.replace("Yeahh", "Yehh");

Is it just replacing the a in Yeah? 它只是取代了是吗? or the first a in the string? 还是字符串中的第一个?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM