What is the regular expression for replaceAll() function to replace "N/A" with "0" ?
input : N/A
output : 0
Oscar Mederos
30k25 gold badges91 silver badges128 bronze badges
asked Jul 7, 2009 at 13:42
penguru
4,37611 gold badges48 silver badges57 bronze badges
3 Answers 3
Assuming s is a String.
s.replaceAll("N/A", "0");
You don't even need regular expressions for that. This will suffice:
s.replace("N/A", "0");
answered Jul 7, 2009 at 13:42
cletus
627k169 gold badges922 silver badges945 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Why use a regular expression at all? If you don't need a pattern, just use replace:
String output = input.replace("N/A", "0");
answered Jul 7, 2009 at 13:43
Jon Skeet
1.5m895 gold badges9.3k silver badges9.3k bronze badges
3 Comments
SteveT
The Java API describes the first argument as a regular expression. Hence the form of the question.
Jon Skeet
@SteveT: Yes, but my point is that there's no need to use
replaceAll at all.SteveT
Ah - thanks. I didn't notice the different method you suggested. That's good to know.
You can try a faster code. If the string contains only N/A:
return str.equals("N/A") ? "0" : str;
if string contains multiple N/A:
return join(string.split("N/A"), "0")
+ (string.endsWith("N/A") ? "0" : "");
where join() is method:
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
2 Comments
Nayuki
I will assume your code works correctly, but what makes you think that calling
split() plus join() is faster than replace() or regex?Koss
I tested on large data sets. Unfortunately the test was lost. I think that you can make a new test in the new version of Java. It will be interesting to see the result. I will be glad to help you.
lang-java