Word highlighting in Qt using QRegExp


Highlight a searched word using QRegExp.

The QRegExp class provides pattern matching using regular expressions.QRegExp is modeled on Perl's regexp language. It fully supports Unicode. QRegExp can also be used in a simpler, wildcard mode that is similar to the functionality found in command shells. The syntax rules used by QRegExp can be changed with setPatternSyntax(). In particular, the pattern syntax can be set to QRegExp::FixedString, which means the pattern to be matched is interpreted as a plain string, i.e., special characters (e.g., backslash) are not escaped.

Example 1:

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

Output:
A <b>bon mot</b>.


Example 2:

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

Output:
Thi<b>s</b> i<b>s</b> a <b>s</b>ample text.


No comments:

Post a Comment