foo
foo

Reputation: 406

How to match spaces at the strings' beginning using QRegularExpression in qt?

I would like to extract digits from a QString containing space and common, and my code just like this:

QString line = "  3 , 50, 200, \t\t100, 70, +3, 5";

QStringList strList = line.split(QRegularExpression("[,\\s]+"));

qDebug() << strList;

// what I expect
// ("3", "50", "200", "100", "70", "+3", "5")

// while the result is
// ("", "3", "50", "200", "100", "70", "+3", "5")

As you can see, there is an unexpected "" ahead when spaces are at the strings' beginning.

So my question is simple: how to edit the regular expression to remove the front spaces or common?

Thank you for your answers in advance!

Upvotes: 0

Views: 1749

Answers (1)

JKSH
JKSH

Reputation: 2718

Title question: "How to match spaces at the strings' beginning using QRegularExpression in qt?"

Well, your code already matches the space at the beginning of the string. These are the matches:

"3,50,200, \t\t100,70,+3,5"

You need to understand how QString::split() works:

  • If the first character matches, QString::split() will give you an empty string at the start of your result.
  • If the last character matches, QString::split() will give you an empty string at the end of your result.

Note, you also need to watch out for matches at the end of your string:

QString line = "1, 2 \t 3 4  ";
QStringList strList = line.split(QRegularExpression("[,\\s]+"));
// Result: ["1", "2", "3", "4", ""]

You ask QString::split() to exclude the empty strings from your result, by passing the QString::SkipEmptyParts flag.

Other question: "how to edit the regular expression to remove the front spaces or commas?"

You cannot do this just by changing your QRegularExpression. You can exclude the empty strings, or remove the unwanted characters manually.

Final solutions

You can ask QString::split() to exclude the empty strings...

QStringList strList = line.split(QRegularExpression("[,\\s]+"), QString::SkipEmptyParts)

...or remove spaces from the start/end of the string before splitting (QString::trimmed() does exactly that)...

QStringList strList = line.trimmed().split(QRegularExpression("[,\\s]+"))

...or remove spaces and commas from the start/end of the string before splitting

line.remove( QRegularExpression("^[,\\s]+") ); // Remove spaces and commas at the start of the string
line.remove( QRegularExpression("[,\\s]+$") ); // Remove spaces and commas at the end of the string
QStringList strList = line.split(QRegularExpression("[,\\s]+"))

Upvotes: 2

Related Questions