Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C+中的QRegExp+;捕捉字符串的一部分_C++_Regex_Qt_Qregexp - Fatal编程技术网

C++ C+中的QRegExp+;捕捉字符串的一部分

C++ C+中的QRegExp+;捕捉字符串的一部分,c++,regex,qt,qregexp,C++,Regex,Qt,Qregexp,我试图使用Qt在C++应用程序中执行正则表达式。 我以前在C++中用Qt做了类似的正则表达式,但是这个表达式很难。 给定一个在字符串末尾带有可选35;的字符串,我想提取该字符串前面的部分 示例: "blue_dog" should result "blue_dog" "blue_dog_1" should result "blue_dog" "blue_dog_23" should result "blue_dog" 这是我到目前为止的代码,但它还不起作用: QString name = "b

我试图使用Qt在C++应用程序中执行正则表达式。 我以前在C++中用Qt做了类似的正则表达式,但是这个表达式很难。 给定一个在字符串末尾带有可选35;的字符串,我想提取该字符串前面的部分

示例:

"blue_dog" should result "blue_dog"
"blue_dog_1" should result "blue_dog"
"blue_dog_23" should result "blue_dog"
这是我到目前为止的代码,但它还不起作用:

QString name = "blue_dog_23";
QRegExp rx("(.*?)(_\\d+)?");    
rx.indexIn(name);
QString result = rx.cap(1);  
我甚至在许多变体中尝试了以下附加选项,但运气不佳。我上面的代码总是以“”结尾:


下面的解决方案应该按照您的要求工作

^[^\s](?:(?!\ud*\n)。*/gm

基本上,这意味着匹配所有内容,但不包括
\ud*\n
。这里,
\ud*\n
表示匹配
\ucode>字符,然后匹配任意数量的数字
\d*
,直到到达新行标记
\n
<代码>
是一个负前瞻,而
?:
是一个非捕获组。基本上,这种组合意味着
?:
后面的序列是表示应该捕获的内容的非包容性端点的组

^[^\s]
告诉表达式从行首开始匹配,只要第一个字符不是空白


/gm
设置全局标志(允许返回多个匹配)和多行标志(这允许序列通过一行进行匹配。

有时不将所有内容打包在单个regexp中更容易。在您的情况下,可以将操作限制在现有
后缀的情况下。否则,结果是
名称

QString name = "blue_dog_23";
QRegExp rx("^(.*)(_\\d+)$");
QString result = name;
if (rx.indexIn(name) == 0)
    result = rx.cap(1);
或者,您可以拆分最后一位并检查它是否为数字。一种紧凑(但可能不是最可读的)解决方案:

QString name = "blue_dog_23";
int i = name.lastIndexOf('_');
bool isInt = false;
QString result = (i >= 0 && (name.mid(i+1).toInt(&isInt) || isInt)) ? name.left(i) : name;

太棒了!谢谢蒂姆。
QString name = "blue_dog_23";
int i = name.lastIndexOf('_');
bool isInt = false;
QString result = (i >= 0 && (name.mid(i+1).toInt(&isInt) || isInt)) ? name.left(i) : name;