Getting an index of match using QRegExp.



  • Hello, when I tried to write an simple module to remove multi-line comments from cpp file I've got a problem with getting an index of begin and end of comment section.

    I merged the whole of file into one QString called "text" in code below.
    @
    QRegExp rx = QRegExp("\/\"); // matches begin of comment section
    QRegExp rx2 = QRegExp("\
    \/"); // matches end of comment section

    qDebug() << rx.indexIn(this->text); // returns corrrectly one, first index but I need all of them so I think I need to use code below
    qDebug() << rx.pos(1);          // returns -1 so It didn't match
    qDebug() << rx.pos(2);        // same here
    

    @

    Sample output:
    @

    Starting /home/piotrek/dev/qt/scs_finder-build-desktop/scs_finder...

    "#include <boost/lambda/lambda.hpp> /* Sample / #include <iostream> #include <iterator> #include <algorithm> int main() { using namespace boost::lambda; typedef std::istream_iterator<int> in; / Annother sample */ std::for_each( in(std::cin), in(), std::cout << (_1 * 3) << " " ); } "

    35
    -1
    -1
    @

    I'll be very happy if someone could give me a tip how to resolve this problem.
    Greetings,
    Piotrek



  • Since your using QString, something like this maybe?

    @#include <QtCore/QRegExp>
    #include <QtCore/QDebug>

    int main()
    {
    QString s1 = "1: Some code commented /* this is a comment / more code";
    //QString s1 = "1: Some code commented /
    this is a comment more code";

    int start = s1.indexOf( "/*" );
    int end = s1.indexOf( "*/" );
    
    if( end > start ){
        QString tmpStr;
        for( int i = start; i <= end+1; ++i ){
            tmpStr.append( s1[i] );
        }
        qDebug() << tmpStr;
    } else {
        qDebug() << "Invalid comment found:\n\t" << s1;
    }
    

    }@



  • [quote author="Richard Neal" date="1314968851"]
    @
    QString tmpStr;
    for( int i = start; i <= end+1; ++i ){
    tmpStr.append( s1[i] );
    }
    @
    [/quote]

    QString::mid().



  • Sure - (would need to calculate length you want from pos in that case).

    Like:
    @#include <QtCore/QRegExp>
    #include <QtCore/QDebug>

    int main()
    {
    QString s1 = "1: Some code commented /* this is a comment / more code";
    //QString s1 = "1: Some code commented /
    this is a comment more code";

    int start = s1.indexOf( "/*" );
    int end = s1.indexOf( "*/" );
    
    if( end > start ){
        qDebug() << s1.mid( start, end-start+2 );
    } else {
        qDebug() << "Invalid comment found:\n\t" << s1;
    }
    

    }@



  • Thanks for all replies, that is what I needed :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.