c++ - Qt C++ QRegExp 解析字符串

标签 c++ regex qt

我有字符串 str。我想得到两个字符串('+' 和 '-'):

QString str = "+asdf+zxcv-tyupo+qwerty-yyuu oo+llad dd ff";

// I need this two strings:
// 1. For '+': asdf,zxcv,qwerty,llad dd ff
// 2. For '-': tyupo,yyuu oo


QRegExp rx("[\\+\\-](\\w+)");
int pos = 0;

while ((pos = rx.indexIn(str, pos)) != -1) {
    qDebug() << rx.cap(0);
    pos += rx.matchedLength();
}

我需要的输出:

"+asdf" 
"+zxcv" 
"-tyupo" 
"+qwerty" 
"-yyuu oo" 
"+llad dd ff" 

我得到的输出:

"+asdf" 
"+zxcv" 
"-tyupo" 
"+qwerty" 
"-yyuu" 
"+llad" 

如果我用 .* 替换 \\w 输出是:

"+asdf+zxcv-tyupo+qwerty-yyuu oo+llad dd ff"

最佳答案

您可以使用以下正则表达式:

[+-]([^-+]+)

参见 regex demo

正则表达式分解:

  • [+-] - +-
  • ([^-+]+) - 匹配除 -+ 之外的 1 个或多个符号的捕获组。

关于c++ - Qt C++ QRegExp 解析字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33630556/

相关文章:

c++ - 比较字符会导致总线错误

c++ - 用户提供的 std::allocator 特化

python - 使用正则表达式选择文本的特定部分

c++ - LeapMotion、Qt 和信号

c++ - QProcess 输出不显示

c++ - 为对象 ID 选择随机数?

c++ - 当添加到另一个小部件时,qt 小部件重叠

java - 正则表达式找不到整个字符串的匹配项

regex - 在 HTML 标签中查找数字的正则表达式

c++ - QT 中 QDoubleSpinBoxes 的多个范围