has - 10 months ago 75

C++ Question

I want to split a string

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

into

`[A ]`

`[B 1]`

`[C 2]`

`[D 254]`

`[E 0]`

I have tested the expression

`\[(.*?)\]`

`QRegExp`

`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 Source

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:

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("[") + ")"));