2

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

3 Answers 3

14

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
Sign up to request clarification or add additional context in comments.

Comments

8

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

3 Comments

The Java API describes the first argument as a regular expression. Hence the form of the question.
@SteveT: Yes, but my point is that there's no need to use replaceAll at all.
Ah - thanks. I didn't notice the different method you suggested. That's good to know.
0

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

answered Oct 18, 2012 at 3:59

2 Comments

I will assume your code works correctly, but what makes you think that calling split() plus join() is faster than replace() or regex?
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.