PDA

View Full Version : Creating QRegExp



namitha
16th November 2016, 10:14
Hi,
Please help me on doing this.
I have a lineedit in which user can enter something like 12-24,67-90.
Actually user is entering range of values. If user is entering anything other than numbers,hyphen and comma it should pop up data is not valid.
How to form a QRegExp for this and is it a right way to check it using ui->lineEdit->hasAcceptableInput function?

Thanks in advance,
Namitha

d_stranz
16th November 2016, 19:35
Look at QRegExpValidator or QRegularExpressionValidator. You can create an instance of that class and install it on your line edit. The regular expression you use will depend on the requirements on the user input. For the string you have indicated above, a regular expression that will accept it is:


^[1-9][0-9]*-[1-9][0-9]*\,[1-9][0-9]*-[1-9][0-9]*

which assumes that there can be one- or two-digit numbers and that a leading zero is not required. It also assumes that a range is required. A string such as "9-20,22" will not pass, for example. On the other hand, it will accept "20-9,8-1", which might not be what you want. You can also use regular expressions with QString::split() to extract the pieces of the line input text once it has passed validation.

Qt's regular expression syntax is based on Perl. You can read about Perl's RE syntax here (http://perldoc.perl.org/perlre.html).

namitha
17th November 2016, 04:50
Hi,
Thank you for the reply. I am going to look on Qt RegExp syntax.
Namitha

jefftee
17th November 2016, 06:42
I would recommend QRegularExpression over QRegExp for new development. The regex below fits your requirement I believe:


^(?:\d+(?:-\d+)*)(?:,\d+(?:-\d+)*)*$

It will match on any of the following:


1,2,3
11,22,33
1-2
1-2,3
1,2-3,4
1-2,3-4
1,2,3-4

The regex shown may also work with QRegExp, but I didn't try it.