java java替换所有()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1092416/
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
java replaceAll()
提问by penguru
What is the regular expression for replaceAll()function to replace "N/A" with "0" ?
replaceAll()用“0”替换“N/A”的函数的正则表达式是什么?
input : N/A
output : 0
输入:N/A
输出:0
回答by cletus
Assuming s is a String.
假设 s 是String。
s.replaceAll("N/A", "0");
You don't even need regular expressions for that. This will suffice:
你甚至不需要正则表达式。这就足够了:
s.replace("N/A", "0");
回答by Jon Skeet
Why use a regular expression at all? If you don't need a pattern, just use replace:
为什么要使用正则表达式?如果您不需要模式,只需使用replace:
String output = input.replace("N/A", "0");
回答by Koss
You can try a faster code. If the string contains only N/A:
您可以尝试更快的代码。如果字符串仅包含 N/A:
return str.equals("N/A") ? "0" : str;
if string contains multiple N/A:
如果字符串包含多个 N/A:
return join(string.split("N/A"), "0")
+ (string.endsWith("N/A") ? "0" : "");
where join()is method:
其中join()是方法:
private String join(String[] split, String string) {
StringBuffer s = new StringBuffer();
boolean isNotFirst = false;
for (String str : split) {
if (isNotFirst) {
s.append(string);
} else {
isNotFirst = true;
}
s.append(str);
}
return s.toString();
}
it is twice as fast
它的速度是原来的两倍

