Reputation: 5758
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
Reputation: 626689
The main issue with your regex is that backslashes must be doubled.
So, there are 2 solutions:
.*?
doubling the backslashes ("\\[(.*?)\\]"
) Sample:
QRegularExpression regex("\\[(.*?)\\]");
QRegularExpressionMatch match = regex.match(strProcessed);
QString textYouWant = match.captured(1);
[^\\]\\[]*
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
Reputation: 10340
Simply try this pattern:
\\[([^\\]]*)
So $1
is containing expected result.
Upvotes: 1