QRegExp issue
-
Hi! I want to remove special characters from
QLineEdit
text.Code:
qDebug() << htmlCharsCheck(ui->lineEdit->text());
QString Test::htmlCharsCheck(QString userInput) { QString testStr = userInput; testStr.remove(QRegExp(QString::fromUtf8("[-`~!@#$%^&*()_—+=|:;<>«»,.?/{}\'\"\\[\\]\\]"))); return testStr; }
The problem is that it doesn't remove those characters from the
QString
. For example it returns<b>[b][/b]
.
How to fix it? Thanks. -
Hi @Cobra91151,
Side note:
QRegularExpression
supersedesQRegExp
- see http://doc.qt.io/qt-5/qregularexpression.html#notes-for-qregexp-users for example.Anyway, there's a few problems with the pattern: the escapes are not right, for example
'
doesn't need escaping, nor does the final]
, and the second-last\]
should be\\]
. The pattern should be:testStr.remove(QRegExp(QString::fromUtf8("[-`~!@#$%^&*()_—+=|:;<>«»,.?/{}'\"[\\]]")));
Also, depending on your needs, you might be better off with something like this instead:
testStr.remove(QRegExp(QString::fromUtf8("[^a-zA-Z \\s]")));
Or perhaps even:
return testStr.toHtmlEscaped();
Which does give quite a different result for your sample input, but might be more in line with what you want to achieve?
Cheers.
-
Yes, it's working well. Thank you.