Reputation: 803
I have the string str
. I want to get two strings ('+' and '-'):
QString str = "+asdf+zxcv-tyupo+qwerty-yyuu oo+llad dd ff";
// I need this two strings:
// 1. For '+': asdf,zxcv,qwerty,llad dd ff
// 2. For '-': tyupo,yyuu oo
QRegExp rx("[\\+\\-](\\w+)");
int pos = 0;
while ((pos = rx.indexIn(str, pos)) != -1) {
qDebug() << rx.cap(0);
pos += rx.matchedLength();
}
Output I need:
"+asdf"
"+zxcv"
"-tyupo"
"+qwerty"
"-yyuu oo"
"+llad dd ff"
Output I get:
"+asdf"
"+zxcv"
"-tyupo"
"+qwerty"
"-yyuu"
"+llad"
If I replace \\w
by .*
the output is:
"+asdf+zxcv-tyupo+qwerty-yyuu oo+llad dd ff"
Upvotes: 2
Views: 1547
Reputation: 626689
You can use the following regex:
[+-]([^-+]+)
See regex demo
The regex breakdown:
[+-]
- either a +
or -
([^-+]+)
- a capturing group matching 1 or more symbols other than -
and +
.Upvotes: 4
Reputation: 29966
Your regexp is excessive:
[\\+\\-](\\w+)
\______/\____/
^ ^--- any amount of alphabetical characters
^--- '+' or '-' sign
So what you are capturing is the +
/-
sign, and any word that follows it directly. If you want to capture only the +
/-
signs, use [+-]
as a regular expression.
EDIT:
To get the strings including the spaces, you need
QRegExp rx("[+-](\\w|\\s)+");
Upvotes: 2