Search code examples
regexqtqstringqregexp

Word highlighting in Qt using QRegExp


I am trying to highlight a searched word using QRegExp.

This is the code.

QString text = "A <i>bon mot</i>.";
text.replace(QRegExp("<i>([^<]*)</i>"), "<b>\\1</b>");
//Output: "A <b>bon mot</b>."

The above code is working, but the below code is not working.

QString text1 = "This is a sample text.";
text1.replace(QRegExp("s"), "<b>\\1</b>");
//Output: "Thi<b>\1</b> i<b>\1</b> a <b>\1</b>ample text."

Solution

  • In regular expressions, \1 corresponds to the first matched group. Groups are parts of the regular expression in parentheses. For example matching the string "hello world" against regexp (hello)([.*]) will have \1 corresponding to "hello" and \2 to " world".

    In your second snippet,

    text1.replace(QRegExp("s"), "<b>\\1</b>");
    

    you do not use parentheses, so there is no group \1 would refer to.

    Use

    text1.replace(QRegExp("(s)"), "<b>\\1</b>");