Search code examples
qtqregexpqregularexpression

How to remove the first character if it's a comma using QRegExp?


I have the following QRegExpValidator

QRegExpValidator doubleValidator = new QRegExpValidator(QRegExp("[-+]?[0-9]*[\\.,]?[0-9]+([eE][-+]?[0-9]+)?"));

It's supposed to be a Double numbers validator that accepts numbers, only one "e" sign, one comma OR dot and one + or - sign at the beggining of the string or after the "e" sign. It works for every case, except that it allows the string to start with a comma or dot. I tried to use [^\\.,] and variations and they did in fact work, but in this case, it would also allow to put two +- signs.

How can I make this to work?


Solution

  • The [-+]?[0-9]*[.,]?[0-9]+([eE][-+]?[0-9]+)? pattern allows the , or . at the start because [-+]? and [0-9]* can match empty strings due to the ? (one or zero occurrences) and * (zero or more occurrences) quantifiers, and then [.,] matches a single occurrence of . or ,. Besides, if the method you are using does not anchor the pattern by default, you also need ^ and $ anchors around the pattern.

    I suggest fixing that with

    "^[-+]?[0-9]+([.,][0-9]+)?([eE][-+]?[0-9]+)?$"
     ^          ^^^^^^^^^^^^^^                  ^ 
    

    Note you do not need to escape the dot inside a character class, [.] always matches a dot char only.

    The [0-9]+([.,][0-9]+)? matches 1+ digits and then an optional sequence of a . or , followed with 1+ digits.