SPlatten
SPlatten

Reputation: 5762

QT Regular Expression getting contents between brackets

I want to split an expression getting the contents between brackets:

eg. An expression could look like this:

    (center:SCREEN)-(25%:SCREEN_WIDTH)

So far my code looks like this:

    QStringList lstTerms = strProcessed.split("/\(([^)]+)\)/")

But this only returns:

    (center:SCREEN)-(25%:SCREEN_WIDTH)

What I want is the array to contain two element, in the case of the example above:

    [0] center:SCREEN
    [1] 25%:SCREEN_WIDTH

Thank you @noob, final routine:

QRegularExpression regex("(?<=\\()[^)]*(?=\\))");
QRegularExpressionMatchIterator matches = regex.globalMatch(strProcessed);
QStringList slstTerms;

while( matches.hasNext() ) {
    QRegularExpressionMatch match = matches.next();

    if (match.hasMatch()) {
        slstTerms.append(match.captured(0));
    }
}

Upvotes: 1

Views: 1937

Answers (1)

user2705585
user2705585

Reputation:

Try with look around assertions. Keep the global mode on with g

Regex: (?<=\()[^)]*

Explanation:

  • (?<=\() looks behind for a ( i.e opening parenthesis.

  • [^)]* matches content within parenthesis until a closing parenthesis ) is met.

Regex101 Demo


Update:

I have changed regex a little. Removed the look ahead part (?=\)) because it was unnecessary. [^)]* itself is checking till a closing parenthesis is met.

Upvotes: 2

Related Questions