Qt - 拆分 QString,使用几种类型的空格作为分隔符

Qt - splitting a QString, using several types of whitespace as separators

我想拆分 QString。 QString中有几个单词,由以下符号中的一个或多个(!)分隔:

我只想提取单词。基本上,我试图复制 Python str.split() 函数的行为。

我知道我可以使用正则表达式来实现这一点,但它会是什么样子?也欢迎任何其他实现此目的的直接方法。

请注意,CR、LF 和制表符 已经是空白。如果您需要匹配空格,您可以依赖 shorthand character class \s:

\s Matches a whitespace character (QChar::isSpace()).

所以,使用 then

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

如果您打算用特定字符拆分字符串,请使用 character class

[...] Sets of characters can be represented in square brackets, similar to full regexps. Within the character class, like outside, backslash has no special meaning.

然后,尝试

QStringList list = str.split(QRegExp("[\r\n\t ]+"), QString::SkipEmptyParts);

您可以稍后在要求更改时扩大列表。