2

I'm trying to get with a QRegularExpression all one-line comments starting by a '#'. I use globalMatch and and an iterator but it doesn't manage to find the "nested comments".

I use this regex : #[^\n]*

And with the following code :

const QString text { "Here # A test with some #comments" };
const QRegularExpression pattern { "#[^\n]*" };

QRegularExpressionMatchIterator it = pattern.globalMatch(text);
while (it.hasNext())
{
    const QRegularExpressionMatch match = it.next();
    qDebug() << match.capturedTexts()[0];
}

It founds only the global comment starting at "# A test" and not the second one. Is there a way to do that ?

Thanks !

Maluna34
  • 245
  • 1
  • 16

1 Answers1

3

You may use

const QRegularExpression pattern { "(?=(#.*))" };
QRegularExpressionMatchIterator it = pattern.globalMatch(text);
while (it.hasNext())
{
    const QRegularExpressionMatch match = it.next();
    qDebug() << match.captured(1);
}

See the regex demo

BTW, with QRegularExpressionMatch::captured, you can directly get the value of any capturing group you need.

The (?=(#.*)) pattern is a positive lookahead that tests each position inside the input string from left to right, and captures into Group 1 a # followed with any 0+ chars other than line break chars as many as possible.

Note that unlike QRegExp, . in the QRegularExpression does not match line breaks, so [^\n] can safely be replaced with ..

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Not bad ! :) But it doesn't return "# A test with some #comments" and "#comments", only "# A test with some " and "#comments". I think I can fix it programmatically but is it the only way ? – Maluna34 Apr 09 '19 at 09:52
  • @Maluna34 So you want to get `# A test with some #comments` and `#comments`? Well, you may concat the two but let me see. – Wiktor Stribiżew Apr 09 '19 at 09:54
  • Wouah incredible ! I didn't think that it was possible !! Thanks !! – Maluna34 Apr 09 '19 at 12:11