Search code examples
c++regexparsingqregexp

Non greedy condition to ignore Comments in a line using QRegExp


I would like to know/have a qregexp which could extract all integers from a line but stop extracting if the digit resides in a comment section

For Example

    { 20,100,0X0},/*this line contains 2 integers*/

My code

QRegExp("(\\d+)\\}"); 

does the job but is not efficient since the comments can come inside the flower braces

For Example, my Expression WILL NOT WORK IF
{ 20,100/*new comment 2*/,0X0}

So how do I ignore the string inside the comment section using QRegExp and continue to search my expression


Solution

  • I suggest matching all the multiline comments as the first alternative in a regex, and match and capture the digit sequences (i.e. use the capturing group around [0-9]+ pattern):

    QRegExp("/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*/|\\b([0-9]+)\\b")
    

    Now, the digits you need will be in cap(1).

    See the regex demo

    It also looks like you need to use word boundaries around the [0-9]+ pattern to match standalone, "whole-word" digit chunks.

    Pattern details: