字符串 replaceAll 方法 (Java)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2491935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String replaceAll method (Java)
提问by Mr CooL
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?
任何人都可以给我一些建议来达到我想要的结果?
采纳答案by Bozho
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
. For example, matching all whitespace characters is done using \s
如果您需要比显示的更复杂的示例,请使用replaceAll(..)
并查看java.util.regex.Pattern
. 例如,匹配所有空白字符是使用\s
回答by Hans Ke?ing
You were asking to replace every 'a', and that is what you got.
你要求替换每个'a',这就是你得到的。
Some solutions:
一些解决方案:
- replaceAll(" a ", " ") (note the spaces around the 'a')
- use regex to chek for 'a' surrounded by word barriers (\b if I'm not mistaken)
- replaceAll(" a ", " ") (注意 'a' 周围的空格)
- 使用正则表达式检查被单词障碍包围的“a”(如果我没记错的话,\b)
回答by GustyWind
you should identify the particular "a" to remove
try thisa.replace(" a ", " ");
你应该确定特定的“a”来删除试试这个a.replace(" a ", " ");
回答by jeff porter
a.replace("Yeahh", "Yehh");
Is it just replacing the a in Yeah? or the first a in the string?
是不是只是替换了a中的呀?还是字符串中的第一个 a ?
回答by Amit Dhawan
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 ", " ");