Qt - 从 QString 中提取首字母大写的单词
Qt - Extracting words with the first letter in uppercase from a QString
我有一个名为 text
的长 QString
,我想提取其中所有首字母大写的单词。有什么办法可以用QString::split()
方法分别测试每个单词吗?或者甚至是无需拆分 text
?
的方法
不拆分:
QRegExp rx("\b[A-Z]\w+\b"); // Or "\b[A-Z]\w*\b" if you want to include one-character words
int pos = 0;
while ((pos = rx.indexIn(text, pos)) != -1)
{
QString your_word = rx.cap(); // every word is here
pos += rx.matchedLength();
}
怎么样:
QString text = "Text is long. Or maybe longer. Yay!";
QRegularExpression regexp("[A-Z][^A-Z]*");
QRegularExpressionMatchIterator match = regexp.globalMatch(text);
QVector<QString> vec;
while(match.hasNext())
vec.append(match.next().capturedTexts());
正则表达式匹配从大写字母向前到下一个大写字母的所有内容。然后,由于您想要所有匹配项,因此您遍历它们并将它们保存到 QVector<QString>
(或 QStringList
,如果您愿意,尽管不鼓励使用)。
我有一个名为 text
的长 QString
,我想提取其中所有首字母大写的单词。有什么办法可以用QString::split()
方法分别测试每个单词吗?或者甚至是无需拆分 text
?
不拆分:
QRegExp rx("\b[A-Z]\w+\b"); // Or "\b[A-Z]\w*\b" if you want to include one-character words
int pos = 0;
while ((pos = rx.indexIn(text, pos)) != -1)
{
QString your_word = rx.cap(); // every word is here
pos += rx.matchedLength();
}
怎么样:
QString text = "Text is long. Or maybe longer. Yay!";
QRegularExpression regexp("[A-Z][^A-Z]*");
QRegularExpressionMatchIterator match = regexp.globalMatch(text);
QVector<QString> vec;
while(match.hasNext())
vec.append(match.next().capturedTexts());
正则表达式匹配从大写字母向前到下一个大写字母的所有内容。然后,由于您想要所有匹配项,因此您遍历它们并将它们保存到 QVector<QString>
(或 QStringList
,如果您愿意,尽管不鼓励使用)。