Kapparino
Kapparino

Reputation: 988

Regex: replaces all invalid characters with empty string

I'm trying to create a regex pattern to replace all invalid characters.

Before decimal point and after decimal point I may have any kind of number, so for example: 0.0, 1.0, 150.0, 129.000, 200.999, etc...

I have a following validation regex pattern which I use for validation and matching:

"\\d+(\\.\\d+)*"

But I want to create regex pattern which I can use to validate decimal number and replace all invalid characters or unexpected, by using the string.replaceAll("regex", value);.

Please check below my test values, and what it should return as a result, after replacing all invalid characters.

String[] values = {
    "0", // return 0 - valid
    "0.", // return 0. - valid
    "0.0", // return 0.0 - valid
    "0.0.", // return 0.0 - invalid, because we dont expect another decimal point
    "0.00", // return 0.00 - valid
    "0.00.", // return 0.00 - invalid, because we dont expect antoher decimal point
    "0.000", // return 0.000 - valid
    // etc.
    "10.000.", // return 10.000, this case should not be possible to enter because we dont want 2 decimal point so number like  10.000.00 should not be possible
    "0.0/", // return 0.0, invalid -- any kind of character will be replaced with empty
    "0.0@", // return 0.0, invalid -- any kind of character will be replaced with empty
};

Upvotes: 0

Views: 327

Answers (1)

Samuel Philipp
Samuel Philipp

Reputation: 11040

You can use the regex \D*(\d+\.?\d*)\D* and replace it with the first group $1 (your valid number). Use that in a findValid() method:

public String findValid(String value) {
    return value.replaceAll("\\D*(\\d+\\.?\\d*)\\D*", "$1");
}

You now can use that to find a valid number for a value. To check if the input value is valid you can check if the input equals valid value:

Arrays.stream(values)
        .forEach(s -> {
            String valid = findValid(s);
            System.out.println(s + " => " + valid + " (" + (valid.equals(s) ? "valid" : "invalid") + ")");
        });

This will print:

0 => 0 (valid)
0. => 0. (valid)
0.0 => 0.0 (valid)
0.0. => 0.0 (invalid)
0.00 => 0.00 (valid)
0.00. => 0.00 (invalid)
0.000 => 0.000 (valid)
10.000. => 10.000 (invalid)
0.0/ => 0.0 (invalid)
0.0@ => 0.0 (invalid)

Upvotes: 1

Related Questions