SPlatten
SPlatten

Reputation: 5758

Regular expression to extract content between []

I have an expression:

[training_width]:lofmimics

I want to extract the content between the [], in the above example I want

training_width

I've tried the following:

QRegularExpression regex("\[(.*?)\]");
QRegularExpressionMatch match = regex.match(strProcessed);
QString textYouWant = match.captured(1);

Where strProcessed contains the original text, but so far it didn't work.

Upvotes: 1

Views: 126

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

The main issue with your regex is that backslashes must be doubled.

So, there are 2 solutions:

  • Use the pattern with .*? doubling the backslashes ("\\[(.*?)\\]")

Sample:

QRegularExpression regex("\\[(.*?)\\]");
QRegularExpressionMatch match = regex.match(strProcessed);
QString textYouWant = match.captured(1);
  • Use a negated character class [^\\]\\[]* that matches 0+ characters other than [ and ]:

Sample:

QRegularExpression regex("\\[([^\\]\\[]*)\\]");
QRegularExpressionMatch match = regex.match(strProcessed);
QString textYouWant = match.captured(1);

The difference between them is that the first - since QRegularExpression implements Perl-like regexps - won't match newlines (as . in Perl-like regexps does not match a newline by default, you'd need to specify QRegularExpression::DotMatchesEverythingOption flag). The second one, since it is using a negated character class, will match anything, even newlines, between [ and the next closest ].

Upvotes: 2

Shafizadeh
Shafizadeh

Reputation: 10340

Simply try this pattern:

\\[([^\\]]*)

So $1 is containing expected result.

Online Demo

Upvotes: 1

Related Questions