使用QRegExp替换QString中的单词
Using QRegExp replace words that are in a QString
我有一个包含保留字列表的QString。我需要解析另一个字符串,查找第一个字符串中包含的、以"\"开头的任何单词,并修改这些单词。
示例:
QString reserved = "command1,command2,command3"
QString a = "command1 command2command1 command3 command2 sometext"
parseString(a, reserved) = "<input com="command1"></input> command2command1 <input com="command3"></input> command2 sometext"
我知道我必须使用QRegExp,但我没有找到如何使用QRegExp来检查我声明的列表中是否有单词。你们能帮我吗?
提前感谢
我会将reservedWords
列表拆分为QStringList
,然后对每个保留字进行迭代。然后在字符之前加上前缀(需要在QString中转义),并使用
indexOf()
函数查看输入字符串中是否存在保留字。
void parseString(QString input, QString reservedWords)
{
QStringList reservedWordsList = reserved.split(',');
foreach(QString reservedWord, reservedWordsList)
{
reservedWord = "\" + reservedWord;
int indexOfReservedWord = input.indexOf(reservedWord);
if(indexOfReservedWord >= 0)
{
// Found match, do processing here
}
}
}
如果你想用QRegEx做这项工作,下面是代码:
QString reservedList("command1,command2,command3");
QString str = "\command1 \command2command1 \command3 command2 sometext";
QString regString = reservedList;
regString.prepend("(\\"); \ To match the '' character
regString.replace(',', "|\\");
regString.append(")"); \ The final regString: (\\command1|\\command2|\\command3)
QRegExp regex(regString);
int pos = 0;
while ((pos = regex.indexIn(str, pos)) != -1) {
qDebug() << regex.cap(0);
pos += regex.matchedLength();
}
相关文章:
- 文本文件中的单词链表
- 将 Qvector<uint8_t> 转换为 QString
- 在指针的帮助下,文本文件中单词的频率
- 如何根据单词在文本中出现的概率输出单词
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- 如何用for循环在c++中生成单词三角形
- 将数字转换为单词
- 使用if-else将数字转换为单词
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口
- C++-字符串是否包含一个带有简单循环的单词
- 使用单词"not"作为C ++类的名称会导致VS2019错误
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- C++为一串单词添加空格
- 在C++中查找(奇怪的)字符串中的单词
- QStringList vs list<shared_ptr<QString>> 性能比较C++
- 用相同的前一个单词和相同的后一个单词读取不同的QString?QString::indexOf
- 使用QRegExp替换QString中的单词
- 比较单个单词与qstring数组