1

I'm trying to check for special characters. I tried:

QString test;
test = "Hello";
QRegExp re("[^A-Za-z0-9]");
if (!re.exactMatch(test))
{
   log("False");
}

Which returns False

Also

int icount = test.count(QRegExp("[!@#$%^&()_+]"));

Which returns > 0

I don't know what am I doing wrong!

What I need is to know if a QString contains any other character than the valid: A-Z,a-z,0-9

3
  • your pattern could only match one single (non-letter) character, so if it matches the "h" in "hello", that isn't an "exact" match, it's partial....right? maybe [...]+ ? Commented Jan 27, 2018 at 15:26
  • Also the new QRegularExpression is faster and recommended for new code. Commented Jan 27, 2018 at 15:49
  • Quicker way to test your patterns: regexr.com (there are others also). Once it works there, it will work in Qt (just remember to double up any `\` in the C++ version). Commented Jan 28, 2018 at 1:09

1 Answer 1

1

Try QRegExp::indexIn()

QRegExp re("[^A-Za-z0-9]");
if (re.indexIn("Hello") < 0)
   qDebug() << "No special chars";
else
   qDebug() << "Found at least one special char";

if (re.indexIn("Hello.") < 0)
   qDebug() << "No special chars";
else
   qDebug() << "Found at least one special char";

Output:

No special chars
Found at least one special char
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.