Reputation: 822
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."
Upvotes: 0
Views: 543
Reputation: 797
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>");
Upvotes: 1