has has - 17 days ago 5
C++ Question

Qt Regular expression to split string between [ ]

I want to split a string

[A ] [B 1] [C 2] [D 254] [E 0]


into
[A ]
,
[B 1]
,
[C 2]
,
[D 254]
and
[E 0]
.

I have tested the expression
\[(.*?)\]
online which is working fine, but I am not able to split it using
QRegExp
. The code is given below.

QRegExp rx("\[(.*?)\]"); //RegEx for [----]
QString str("[A ] [B 1] [C 2] [D 254] [E 0] ");
QStringList query = str.split(rx);
for( auto q : query ) {
qDebug() << q;
}


Can anybody point out where I am making the mistake. Thank you.

Answer

What you need to split this string properly are "lookaheads" and "lookbehinds".

QString s("[A ] [B 1] [C 2] [D 254] [E 0]");
QStringList sl = s.split(QRegularExpression("(?<=\\])[ ](?=\\[)"));

Tossing that into a qDebug() << sl; gave me this:

enter image description here

Lets break it down:

  • (?<=\\]) or (?<=PutTextHere)is a "positive lookbehind", which will see if the string behind it matches, but not include it in the match itself.
  • [ ] This could just simply be an empty space: -- I just include the square brackets for readability.
  • (?=\\[) or (?=PutTextHere)is a "positive lookahead"
  • \\[ The reason why you need two escapes, is that the regular expression needs one escape \, and your code will need to escape the escape. An alternative would be:
    QStringList sl = s.split(QRegularExpression("(?<="
                           + QRegularExpression::escape("]")
                           + ")[ ](?="
                           + QRegularExpression::escape("[")
                           + ")"));
Comments