c++qtqstringqregexp

How to replace QRegExp in a string?


I have a string. For example:

QString myString = "Today is Tuesday";

The requirement is: when user types a string, if that string is contained in myString, then that part in the myString should be bold, and case insensitive (Qt::CaseInsensitive), but the format of myString should remain (upper case characters should be upper case and lower case characters should be lower case).

For example:

This is my function:

void myClass::setBoldForMatching( const QString &p_text )
{
  QRegExp regExp( p_text, Qt::CaseInsensitive, QRegExp::RegExp );
  if ( !p_text.isEmpty() )
  {       
    if ( myString.contains( regExp ) )
    {
      myString = myString.replace( p_text, QString( "<b>" + p_text + "</b>" ), Qt::CaseInsensitive );
    }
  }
}

This function is wrong because

user types t -> today is tuesday.

What I need is Today is Tuesday

How should I update my function?


Solution

  • We can use a different QString::replace(), which accepts a QRexExp, to substitute all occurrences. The key to this is that we need a capture group in order to replace the original text in the substitution, using a back-reference (\1):

    #include <QRegExp>
    
    QString setBoldForMatching(QString haystack, const QString& needle)
    {
        if (needle.isEmpty()) return haystack;
        const QRegExp re{"("+QRegExp::escape(needle)+")", Qt::CaseInsensitive};
        return haystack.replace(re, "<b>\\1</b>");
    }
    

    Demo

    #include <QDebug>
    int main()
    {
        qInfo() << setBoldForMatching("THIS DAY (today) is Tuesday.", "Day");
    }
    

    THIS DAY (today) is Tuesday.