Reputation: 981
How can i split a QString
by a character, e.g.: '+'
and do not split when that character is escaped: '\+'
?
Thanks!
As requested, some more detail:
The String to split: "a+\+"
The delimiter: '+'
The desired output: "a"
, "+"
Upvotes: 2
Views: 887
Reputation: 207
If, instead of a "+" as a separator, you can use space as a separator... splitArgs
does the work for you:
https://stackoverflow.com/a/48977326/2660408
Upvotes: 0
Reputation: 38909
You'll want to use the globalMatch
with a regular expression to split that selects everything but a non-escaped '+'
:
(?:[^\\\+]|\\.)*
So given QString foo
you can iterate through the list using a QRegularExpressionMatchIterator
:
QRegularExpression bar("((?:[^\\\\\\+]|\\\\.)*)");
auto it = bar.globalMatch(foo);
while(it.hasNext()){
cout << it.next().captured(1).toStdString() << endl;
}
In C++11 you can also use a cregex_token_iterator
:
regex bar("((?:[^\\\\\\+]|\\\\.)+)");
copy(cregex_token_iterator(foo.cbegin(), foo.cend(), bar, 1), cregex_token_iterator(), ostream_iterator<string>(cout, "\n"));
In the unfortunate event that you have neither Qt5, nor C++11, nor Boost, you can use QRegExp
:
QRegExp bar("((?:[^\\\\\\+]|\\\\.)*)");
for(int it = bar.indexIn(foo, 0); it >= 0; it = bar.indexIn(foo, it)) {
cout << bar.cap(1).toStdString() << endl;
}
Upvotes: 1