【问题标题】:Word highlighting in Qt using QRegExp使用 QRegExp 在 Qt 中突出显示单词
【发布时间】:2015-02-12 15:38:54
【问题描述】:

我正在尝试使用 QRegExp 突出显示搜索的单词。

这是代码。

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

上面的代码可以用,下面的代码不行。

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."

【问题讨论】:

    标签: regex qt qstring qregexp


    【解决方案1】:

    在正则表达式中,\1 对应于第一个匹配的组。组是括号中正则表达式的一部分。例如,将字符串“hello world”与正则表达式(hello)([.*]) 匹配,\1 对应于“hello”,\2 对应于“world”。

    在你的第二个 sn-p 中,

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

    您不使用括号,因此没有\1 可以引用的组。

    使用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      • 2012-11-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 1970-01-01
      相关资源
      最近更新 更多