免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: fwizard
打印 上一主题 下一主题

[C] 如何在C语言中巧用正则表达式 [复制链接]

论坛徽章:
1
双子座
日期:2015-01-04 14:25:06
1 [报告]
发表于 2008-01-01 00:20 |显示全部楼层
在调用函数regexec()进行模式匹配的过程中,可能在字符串string中会有多处与给定的正则表达式相匹配,参数pmatch就是用来保存这些匹配位置的,而参数nmatch则告诉函数regexec()最多可以把多少个匹配结果填充到pmatch数组中。当regexec()函数成功返回时,从 string+pmatch[0].rm_so到string+pmatch[0].rm_eo是第一个匹配的字符串,而从string+pmatch [1].rm_so到string+pmatch[1].rm_eo,则是第二个匹配的字符串,依此类推。

似乎这里有误
应该是以下的解释才对
字符串string中会有多处与给定的正则表达式相匹配,应该是匹配第一个就结束了,pmatch保存的应该是用‘()’括起来的Subexpression的位置
10.3.4 Match Results with Subexpressions

When regexec matches parenthetical subexpressions of pattern, it records which parts of string they match. It returns that information by storing the offsets into an array whose elements are structures of type regmatch_t. The first element of the array (index 0) records the part of the string that matched the entire regular expression. Each other element of the array records the beginning and end of the part that matched a single parenthetical subexpression.
— Data Type: regmatch_t

    This is the data type of the matcharray array that you pass to regexec. It contains two structure fields, as follows:

    rm_so
        The offset in string of the beginning of a substring. Add this value to string to get the address of that part.
    rm_eo
        The offset in string of the end of the substring.

— Data Type: regoff_t

    regoff_t is an alias for another signed integer type. The fields of regmatch_t have type regoff_t.

The regmatch_t elements correspond to subexpressions positionally; the first element (index 1) records where the first subexpression matched, the second element records the second subexpression, and so on. The order of the subexpressions is the order in which they begin.

When you call regexec, you specify how long the matchptr array is, with the nmatch argument. This tells regexec how many elements to store. If the actual regular expression has more than nmatch subexpressions, then you won't get offset information about the rest of them. But this doesn't alter whether the pattern matches a particular string or not.

If you don't want regexec to return any information about where the subexpressions matched, you can either supply 0 for nmatch, or use the flag REG_NOSUB when you compile the pattern with regcomp.

[ 本帖最后由 yecheng_110 于 2008-1-1 00:25 编辑 ]
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP