简体   繁体   中英

regex replace all invalid characters except minus character “-” at first index of a string

I'm using the following regex to replace all invalid characters which exist in the decimal number string:

final String REGEX_REPLACE_INVALID_DECIMAL_NUMBER_CHARACTERS = "\\D*(\\d+\\.?\\d*)\\D*";

This is my test code:

    String[] inputs = {
        "0a", // -> 0
        "a0a.0", // -> 0.0
        "b0a.t1c", // -> 0.1
        "-a0b.c1d", // -> -0.1
        "-#0.t12[3]", // -> -0.123
        "-123.[1]2_3", // -> -123.123
    };

    final String REPLACE_INVALID_DECIMAL_NUMBER_CHARACTERS = "\\D*(\\d+\\.?\\d*)\\D*";
    for (String input : inputs) {
        String replaceInvalidDecimalNumberCharacters = input.replaceAll(REPLACE_INVALID_DECIMAL_NUMBER_CHARACTERS, "$1");
        System.out.println("input: " + input +
                "\n\treplaceInvalidDecimalNumberCharacters: " + replaceInvalidDecimalNumberCharacters);
    }

Currently my regex, replaces all invalid characters even decimal poinit and minus at first index of a string.

How can I exclude removing minus and decimal point?

This is my test output:

input: 0a   replaceInvalidDecimalNumberCharacters: 0
input: a0a.0    replaceInvalidDecimalNumberCharacters: 00
input: b0a.t1c  replaceInvalidDecimalNumberCharacters: 01
input: -a0b.c1d replaceInvalidDecimalNumberCharacters: 01
input: -#0.t12[3]   replaceInvalidDecimalNumberCharacters: 0.123
input: -123.[1]2_3  replaceInvalidDecimalNumberCharacters: 123.123

I suggest proceeding with regex using two steps. First, strip off all irrelevant characters from the input string. Then, use another regex to check if what remains after the first replacement be a valid number:

String input = "-123.[1]2_3";
input = input.replaceAll("[^0-9.-]+", "");
if (input.matches("-?\\d+(?:\\.\\d+)?")) {
    System.out.println("Found a valid number: " + input);
}
else {
    System.out.println("Input is invalid");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM