Qt C++QRegExp解析字符串

Qt C++ QRegExp parse string

本文关键字:字符串 C++QRegExp Qt      更新时间:2023-10-16

我有字符串str。我想要两个字符串("+"answers"-"):

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演示

正则表达式分解:

  • [+-]-+-
  • CCD_ 7-匹配除-+之外的1个或多个符号的捕获组

您的正则表达式过多:

[\+\-](\w+)
______/____/
    ^     ^--- any amount of alphabetical characters
    ^--- '+' or '-' sign

因此,您捕获的是+/-符号,直接跟在它后面的任何单词。如果只想捕获+/-符号,请将[+-]用作正则表达式

编辑:

要获得包含空格的字符串,您需要

QRegExp rx("[+-](\w|\s)+");