Qt - Extracting words with the first letter in uppercase from a QString

1.8k Views Asked by At

I have a long QString named text, and I am looking to extract all the words in it, which have their first letter in uppercase. Is there any way to use the QString::split() method to test each word separately ? Or even a way to do it without having to split text ?

2

There are 2 best solutions below

0
On BEST ANSWER

What about:

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());

The regular expression matches everything from an upper case letter forward until next capital letter. Then since you wanted all the matches you iterate through them and save them to QVector<QString> (or QStringList if you so wish though it is discouraged to use).

1
On

Without splitting:

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();
}