Jackson
Jackson

Reputation: 1526

How to replace occurance of numbers with single value?

I have below code

String str = "/admin/3138/misc";
boolean isNumbers = str.chars().anyMatch(Character::isDigit);
System.out.println(isNumbers);
if (isNumbers) {
    str = str.replaceAll("[0-9]", "%d");
    System.out.println("->" + str);
}

Which gives output:

admin/%d%d%d%d/misc

I need:

admin/%d/misc

So from string if numbers found just replace with %d one only, not every digit.

Upvotes: 0

Views: 54

Answers (2)

k314159
k314159

Reputation: 11140

The answer by m.antkowitz is correct; however, be careful of the risks of code injection. If someone names a directory "/abc/%def/123", and you then translate that into "/abc/%def/%d" and try to use that in a String.format() call, your application will break. To get around this, guard against the occurrence of "%d" in the name:

str = str.replace("%", "%%").replaceAll("[0-9]+", "%d");

This replaces a % with %% which, when printed using printf() or String.format(), causes a literal "%" to be output.

Upvotes: 0

m.antkowicz
m.antkowicz

Reputation: 13571

You need to change your regex to "[0-9]+"

if (isNumbers) {
    str = str.replaceAll("[0-9]+", "%d");
    System.out.println("->" + str);
}

Oracle's doc: Quantifiers

Upvotes: 3

Related Questions