Question

The following piece is not working properly:

  QRegExp exp ("[À-Ÿà-ÿA-Za-z0-9\\-\\_]+");
  if (!formatedName.contains(exp)) {
    success = false;
  }

This block of code is to validate input strings entered by users. It should only accept numbers, french and english characters, dash and underscore.

Actually, the code is almost working. The only problem is that is accept special characters if I enter also legal characters. So, the string "!@#@" will returns false, but string "hell!@^ooo" will return true.

How should I use regex properly to only accept my regular expression?

thank you

Was it helpful?

Solution

I'd suggest adding ^ and $ to indicate that the expression should cover the entire string, not just part of it.

QRegExp exp ("^[À-Ÿà-ÿA-Za-z0-9\\-\\_]+$");
  if (!formatedName.contains(exp)) {
    success = false;
  }

OTHER TIPS

You can specify start and end delimiters to stop the regex from successfully matching strings with any part of the regex contained within them.

"^[À-Ÿà-ÿA-Za-z0-9\\-\\_]+$"

This will ensure that the entire string is checked.

You can also use QRegExp::exactMatch(), which is essentially equivalent to surrouding your regex with the ^ and $ characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top