Not getting what I expected using a regex in QRegExpValidator.

  • I am using a QLineEdit with a QRegExpValidator in order to limit inputs to this type: or d.yellow4 and so on.

    So basically one lowercase character followed by a period and then an arbitrary number of characters and possibly a number at the end.

    What I have are the following

    QRegExp textValidator("^[a-z]+\.?[a-z]+[0-9]*$"); 
    QRegExpValidator *validator = new QRegExpValidator(textValidator, 0);


    QRegExp textValidator("[a-z]\.\w++"); 
    QRegExpValidator *validator = new QRegExpValidator(textValidator, 0);

    With the first one allowing pretty much anything and the second one pretty much nothing (I'm a man of the extremes what can I say).

    Can someone help me fix my validator?

  • Well, the first problem I see here is the escaping. The backslash is being consumed by the C++ compiler and doesn't get to the regex parser. You need to double escape it, to compensate this issue. Like this:


    You said the string can only have one lowercase character, so you need to remove the first +. If both the period and the following characters are optional, they should be grouped.


  • @Leonardo said:


    Thanks for the quick reply. I can confirm it is working as intended.

  • Lifetime Qt Champion


    You can check the regularexpression example (available starting 5.5). It's a little application that helps test and build regexp to use with QRegularExpression

  • 5.5 you say. Interesting :)

  • Lifetime Qt Champion

    I do :)

    However, you don't need to build Qt 5.5 to build it, you can use your current Qt version

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.