regexqtqstringqregexp

QString: Remove first occurance of regular expression


QString has a method remove that takes a QRegExp. It removes every occurrence of the regular expression.

Is there a way to remove only the first occurrence of the regular expression?

Answer to QString replace only first occurrence doesn't help. See comment from Akiva there.


Solution

  • You can use next code:

    QString message = "This is the original text";
    QRegExp rx = QRegExp("is|he", Qt::CaseInsensitive);
    
    if (message.contains(rx)){
        message = message.remove(rx.pos(0), rx.cap(0).size());
    }
    

    The final message is:

    Th is the original text