找回密码
 立即注册
收起左侧

正则表达式用cap捕捉文本的例子.没懂。

5
回复
7608
查看
[复制链接]
累计签到:2 天
连续签到:1 天
来源: 2014-7-29 16:22:53 显示全部楼层 |阅读模式
5Qter豆

QRegExprxlen("(\\d+)(?:\\s*)(cm|inch)");
    int pos3 = rxlen.indexIn("Length:189cm");
    if (pos3 > -1) {
        QString value = rxlen.cap(1);  // 结果为189
        QString unit = rxlen.cap(2);   // 结果为cm
        QString string = rxlen.cap(0); // 结果为189cm
        qDebug() << value << unit<< string;
}
         
         这个正则表达式我大概能看懂。是一个单词,加可能的“:”,加非字母,加cminch
不过我一直不能理解cap这个函数的意思,这里为什么得到这个结果
如果我加个ok的单词改为:
QRegExprxlen("(\\d+)(?:\\s*)(ok)(cm|inch)");
int pos3 = rxlen.indexIn("Length:  ok 189cm");.
           if (pos3 > -1) {
        QString value = rxlen.cap(1);  
        QString unit = rxlen.cap(2);   
        QString string = rxlen.cap(0);
        qDebug() << value << unit<< string;
}
结果就没有了。。。。


Returns the text captured by the nth subexpression. The entire match has index 0 and the parenthesized subexpressions have indexes starting from 1 (excluding non-capturing parentheses).
rxlen("(\\d+)(?:\\s*)(cm|inch)"); int pos = rxlen.("Length: 189cm"); if (pos > -1) {      value = rxlen.cap(1); // "189"      unit = rxlen.cap(2);  // "cm"     // ... }The order of elements matched by cap() is as follows. The first element, cap(0), is the entire matching string. Each subsequent element corresponds to the next capturing open left parentheses. Thus cap(1) is the text of the first capturing parentheses, cap(2) is the text of the second, and so on.
求解

最佳答案

查看完整内容

有书的话可以看下第7.3.3小节的第三段,里面写着呢! (?:)是非捕获括号
回复

使用道具 举报

累计签到:1571 天
连续签到:1 天
2014-7-29 16:22:54 显示全部楼层
caiwei_cs 发表于 2014-7-30 09:47
我就是看了qt creator 里面的章节的例子哦。

(?:\\s*) 我的理解是:

有书的话可以看下第7.3.3小节的第三段,里面写着呢!

(?:)是非捕获括号
回复

使用道具 举报

累计签到:2 天
连续签到:1 天
2014-7-29 16:23:51 显示全部楼层
上面的英文是qt 帮助里面的,我复制过来格式出错了。
回复

使用道具 举报

累计签到:1571 天
连续签到:1 天
2014-7-29 22:15:16 显示全部楼层
你理解错了。建议看下QRegExp类的帮助文档,或者《Qt Creator快速入门》相关章节。

(\\d+)(?:\\s*)(cm|inch) 意思是: 捕获至少一个数字、不捕获空格、捕获cm或inch

cap(0)是匹配的完整文本、cap(1)是匹配的第一个括号、cap(2)是匹配的第二个括号
回复

使用道具 举报

累计签到:2 天
连续签到:1 天
2014-7-30 09:47:11 显示全部楼层
yafeilinux 发表于 2014-7-29 22:15
你理解错了。建议看下QRegExp类的帮助文档,或者《Qt Creator快速入门》相关章节。

(\\d+)(?:\\s*)(cm|inc ...

我就是看了qt creator 里面的章节的例子哦。

(?:\\s*) 我的理解是:
? 我不明白意思。 E?表示 E{0,1},但这里?在开头,而不是一个字符的后面。
: 表示字符:。
\\s* 表示 0个或者多个\s及空白符。

为什么cap(1)不是针对(?:\\s*)
而是(cm|inch) 呢?
回复

使用道具 举报

累计签到:2 天
连续签到:1 天
2014-8-9 10:36:44 显示全部楼层
yafeilinux 发表于 2014-8-1 09:58
有书的话可以看下第7.3.3小节的第三段,里面写着呢!

(?:)是非捕获括号 ...

谢谢,是我没看仔细。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

公告
可以关注我们的微信公众号yafeilinux_friends获取最新动态,或者加入QQ会员群进行交流:190741849、186601429(已满) 我知道了