简体   繁体   English

正则表达式替换字符串的第一个索引处除减号“-”以外的所有无效字符

[英]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. 目前,我的正则表达式替换了所有无效字符,包括字符串的第一个索引处的十进制poinit和减号。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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