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

有帮助吗?

解决方案

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;
  }

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top