Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt Regular expression to split string between [ ]

Tags:

c++

regex

qt

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.

like image 212
Oli Avatar asked Feb 26 '26 15:02

Oli


1 Answers

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("[")
                           + ")"));
like image 180
Anon Avatar answered Mar 01 '26 05:03

Anon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!