PDA

View Full Version : QRegExp for removing all non alphanumeric charecters



vladozar
27th October 2009, 02:42
Using QString I can remove any character from string, but what would be QRegExp to remove ALL non alphanumeric characters from that string. Currently I have written a function that will remove each character one by one, but I would like to know if i can do the same thing only in one step.

Here is my function


QString clean(QString str)
{
str.remove("\"");
str.remove("\\");
str.remove(".");
str.remove(",");
str.remove("?");
str.remove("!");
str.remove("'");
str.remove("`");
str.remove("-");
str.remove("_");
str.remove("—");
str.remove("@");
str.remove("#");
str.remove("$");
str.remove("%");
str.remove("^");
str.remove("&");
str.remove("*");
str.remove("(");
str.remove(")");
str.remove("{");
str.remove("}");
str.remove("[");
str.remove("]");
str.remove("|");
str.remove(";");
str.remove(":");
str.remove("/");
str.remove(">");
str.remove("<");
str.remove("~");
str.remove("=");
str.remove("+");
str.remove(str.fromUtf8("«"));
str.remove(str.fromUtf8("»"));
str = str.trimmed();
return str;
}

calhal
27th October 2009, 09:58
Read the QRegExp class description in QtAssistant.
I guess you want something similar to:

str.remove(QRegExp("[^a-zA-Z\\d\\s]"));
but maybe there is a better way to write it ;)

vladozar
31st October 2009, 18:41
Thanks for suggestion.
After some reading and trial&error here is the code that works


str.remove(QRegExp(QString::fromUtf8("[-`~!@#$%^&*()_—+=|:;<>«»,.?/{}\'\"\\\[\\\]\\\\]")));

This will remove all none alphanumeric characters that i know.
If anyone will use this code, save the file in UTF-8, otherwise it will not remove — «»

Jencek
8th March 2011, 16:57
Seems to be working (Calhal's solution would work only with ascii - no interpunction characters).

Maximus2
16th October 2015, 16:13
Hey, Sorry to revive an old thread.

I am using your solution:


QString Util::cleanQString(QString toClean) {

QString toReturn = toClean;
toReturn.remove(QRegExp(QString::fromUtf8("[-`~!@#$%^&*()_—+=|:;<>«»,.?/{}\'\"\\\[\\\]\\\\]")));
return toReturn;
}

The compiler is giving me theses 4 warnings that I would like to fix:
warning: C4129: '[' : unrecognized character escape sequence
warning: C4129: ']' : unrecognized character escape sequence
warning: C4129: '[' : unrecognized character escape sequence
warning: C4129: ']' : unrecognized character escape sequence

Using Qt 5.5.0 on VS2013