penguru
penguru

Reputation: 4370

java replaceAll()

What is the regular expression for replaceAll() function to replace "N/A" with "0" ?

input : N/A
output : 0

Upvotes: 2

Views: 18228

Answers (3)

Koss
Koss

Reputation: 1012

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

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

Why use a regular expression at all? If you don't need a pattern, just use replace:

String output = input.replace("N/A", "0");

Upvotes: 8

cletus
cletus

Reputation: 625007

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");

Upvotes: 14

Related Questions