Reputation: 362
I want to create a program that validate user input. I have found a Regex that validates if the input is correct or not. The problem is that the program allows the user to enter extra characters which are not part of the correct input. For instance the correct input is 23km, it allows the user to put something like 23rt that's what I want to eliminate. Here is my code:
QRegExp r1("\\d{1,}(km|hm|dam|m|dm|сm) \\d{1,2}(km|hm|dam|m|dm|сm) x \\d{1,}(km|hm|dam|m|dm|сm) \\d{1,2}(km|hm|dam|m|dm|сm)");
if(input.isEmpty()) return QValidator::Intermediate;
if(r1.exactMatch(input)) return QValidator::Acceptable; else
return QValidator::Intermediate;
I tried return QValidator::Invalid;
at the end and it does not take inputs at all.
I want to make something in form of: (23km 3m X 1km 4m).
Upvotes: 0
Views: 557
Reputation: 396
I think you might be making a mistake in getting the input string that is being passed to this function. std::cin automatically breaks at spaces, make sure you are using std::getline. The below code appears to work for me.
#include <QtCore/QRegularExpression>
#include <QtCore/QString>
#include <string>
#include <QtGui/QValidator>
#include <iostream>
QValidator::State test(QString input)
{
QRegularExpression r1("\\d{1,}(km|hm|dam|m|dm|сm) \\d{1,2}(km|hm|dam|m|dm|сm) x \\d{1,}(km|hm|dam|m|dm|сm) \\d{1,2}(km|hm|dam|m|dm|сm)");
//QRegExp r1(".*\\d{1,}(km|hm|dam|m|dm|сm) \\d{1,2}(km|hm|dam|m|dm|сm).*");
//QRegularExpression r1("test test");
if(input.isEmpty()) return QValidator::Intermediate;
if(r1.match(input).hasMatch()) return QValidator::Acceptable;
else return QValidator::Invalid;
}
int main()
{
std::string input;
for (int i = 0; i < 100; i++)
{
std::getline(std::cin, input);
QString test_str = QString::fromStdString(input);
QValidator::State res = test(test_str);
std::cout<<res<<std::endl;
}
return 0;
}
Upvotes: 0