如何在字符串中替换QRegExp? [英] How to replace QRegExp in a string?
问题描述
我有一个字符串.例如:
I have a string. For example:
QString myString = "Today is Tuesday";
要求是:当用户键入字符串时,如果该字符串包含在myString
中,则myString
中的该部分应为粗体且不区分大小写(Qt::CaseInsensitive
),但格式为
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).
例如:
- 用户类型:
tu
->今天是 Tu 星期几 - 用户类型:
ES
->今天是Tu es 天 - 用户类型:
aY
-> Tod ay 是Tuesd ay
- user types:
tu
-> Today is Tuesday - user types:
ES
-> Today is Tuesday - user types:
aY
-> Today is Tuesday
这是我的功能:
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 );
}
}
}
此功能有误,因为
用户类型t
-> t 今天是 t 星期二.
user types t
-> today is tuesday.
我需要的是 T ,今天是 T 星期二
What I need is Today is Tuesday
我应该如何更新我的功能?
How should I update my function?
推荐答案
我们可以使用接受QRexExp
的其他QString::replace()
来替换所有出现的内容.这样做的关键是我们需要一个捕获组,以便使用后向引用(\1
)来替换替换中的原始文本:
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>");
}
演示
#include <QDebug>
int main()
{
qInfo() << setBoldForMatching("THIS DAY (today) is Tuesday.", "Day");
}
这个 DAY (到 day )是星期二 day .
THIS DAY (today) is Tuesday.
这篇关于如何在字符串中替换QRegExp?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!