I have a QString
containing "(M001)" and I want to remove the parentheses in text. The result should be "M001". How should I use a QRegExp
for this?
Asked
Active
Viewed 2,057 times
3

jotik
- 17,044
- 13
- 58
- 123
-
Do you want the regular expression to remove **all** parenthesis, or just '(' in the beginning of the string and ')' at the end of string? – jotik May 19 '16 at 08:05
2 Answers
3
If you know your string always has parenthesis, you could just do something like:
str = str.mid(1); // Remove first character
str.chop(1); // Remove last character
Otherwise you could also do this instead of using a regular expression:
if (str.startsWith('(') && str.endsWith(')')) {
str = str.mid(1); // Remove first character
str.chop(1); // Remove last character
}
But if you insist using a QRegExp
, try this:
str.remove(QRegExp("^\\(|\\)$"));
or this:
str.replace(QRegExp("^\\((.*)\\)$"), "\\1");
EDIT: If you want to remove ALL parenthesis from the string you can try:
str.remove('(').remove(')');
or
str.remove(QRegExp("[()]"));

jotik
- 17,044
- 13
- 58
- 123
3
I see two possible way to do it:
1.Using QString::remove()
like this:
str.remove("(");
str.remove(")");
2.Using QRegExp class like this:
str.remove(QRegExp("[()]"));
In both of variants I get "M001" string. Of course, there are some restrictions: all parentheses will be removed.But seems like it's what you want, don't you?

t3ft3l--i
- 1,372
- 1
- 14
- 21
-
I don't want to use str.remove(")"); so I asked QRegExp and it works. thanks a lot. – May 18 '16 at 13:44