PDA

View Full Version : QRegExp: Last sign has to be a number



forenued
19th January 2016, 13:01
Hello,

i need a regular expression that ensures that the last sign in a QString is a digit and i tried the following code:





QRegExp rx ("[0-9]$");

cout << rx.exactMatch("123") << endl;



i always get false as result, but i don't understand why?

Can anybody tell me what i'm doing wrong?

Thank you very much!

Moppel
19th January 2016, 13:43
Can't test but I think this should work:



QRegExp rx (".*[0-9]$");



Your regexp should match this:


cout << rx.exactMatch("3") << endl;

Does this match?
If so, [0-9]$ machtes one and only one digit (exactMatch)
[0-9] can be written as \d as well, just follow the link to QRegExp

forenued
19th January 2016, 14:44
Thank you for your answer! But with this i get an invalid expression. The error string is:



not valid!: bad repetition syntax


Added after 47 minutes:

Ah, it works with



QRegExp rx (".*[0-9]$");


Thank you very much, Moppel and have a nice day!!

anda_skoa
19th January 2016, 16:06
Alternatively you could check if the last character is a digit.

Cheers,
_

jefftee
20th January 2016, 07:36
With any new code you should look at and use (IMHO) QRegularExpression over QRegExp.

anda_skoa
20th January 2016, 17:16
I agree but using any kind of regular expression looks wasteful if the requirement is to just check the last character, which is basically just an "isDigit" check on the last QChar in the string.

Cheers,
_

jefftee
21st January 2016, 04:32
I agree but using any kind of regular expression looks wasteful if the requirement is to just check the last character, which is basically just an "isDigit" check on the last QChar in the string.
I agree, just couldn't tell if it was a homework assignment for regular expressions, etc!