Alan
Alan

Reputation: 1275

QRegExp does not operate as expected

I have a QString "mystring" which is captured from the return value from this shell command:

    df /storage/sdcard0/ 

The string captured is:

   Filesystem               Size     Used     Free   Blksize
   /storage/sdcard0/        5.5G     3.9G     1.6G   4096

I convert the QString to a QStringList with:

   QStringList list=mystring.split(QRegExp("\\s"));
   int i = list.count();

However, when I examine the list:

  for( int a = 0; a < i; a = a + 1 )
             qDebug() << list[a];

"Filesystem"
""
"Size"
""
"Used"
""
"Free"
""
"Blksize"
""
"/sdcard/"
""
"5.5G"
""
"3.9G"
""
"1.6G"
""
"4096"
""
""

I've omitted a bunch of the "" for brevity. If I use the same split with a typed-in string it works perfectly.

       QString mystring = "This is a sentence with words"

qDebug shows:

"This"
"is"
"a"
"sentence"
"with"
"words"

How can I stop these "" from being added to the QStringList? Can this be corrected with a different QRegExp?

Upvotes: 1

Views: 47

Answers (1)

drescherjm
drescherjm

Reputation: 10857

Looking at QString::split(const QRegExp &rx, SplitBehavior behavior = KeepEmptyParts) const there is an optional parameter SplitBehavior that allows you to specify how to process the empty parts. If you leave the default QString::split() will keep the empty parts. To skip you need to set this to QString::SkipEmptyParts.

So change your split to the following:

QStringList list=mystring.split(QRegExp("\\s"),QString::SkipEmptyParts);

Upvotes: 0

Related Questions