我正在尝试使用正则表达式从另一个字符串中提取一个字符串。我正在使用POSIX正则表达式函数(
例如,让模式简单点,如
我想捕获在'<'和'>'之间的所有内容。
我的问题是
我错过了什么吗?
提前感谢,
编辑:一些代码
regcomp, regexec
...),但是我无法捕获一个组...例如,让模式简单点,如
"MAIL FROM:<(.*)>"
(带有REG_EXTENDED
cflags)我想捕获在'<'和'>'之间的所有内容。
我的问题是
regmatch_t
给出整个模式(MAIL FROM:<...>)的边界,而不仅仅是圆括号内的内容...我错过了什么吗?
提前感谢,
编辑:一些代码
#define SENDER_REGEX "MAIL FROM:<(.*)>"
int main(int ac, char **av)
{
regex_t regex;
int status;
regmatch_t pmatch[1];
if (regcomp(®ex, SENDER_REGEX, REG_ICASE|REG_EXTENDED) != 0)
printf("regcomp error\n");
status = regexec(®ex, av[1], 1, pmatch, 0);
regfree(®ex);
if (!status)
printf( "matched from %d (%c) to %d (%c)\n"
, pmatch[0].rm_so
, av[1][pmatch[0].rm_so]
, pmatch[0].rm_eo
, av[1][pmatch[0].rm_eo]
);
return (0);
}
输出:
$./a.out "012345MAIL FROM:<abcd>$"
matched from 6 (M) to 22 ($)
解决方案:
如RarrRarrRarr所说,索引确实在pmatch[1].rm_so
和pmatch[1].rm_eo
中。
因此,regmatch_t pmatch[1];
变成了regmatch_t pmatch[2];
并且regexec(®ex, av[1], 1, pmatch, 0);
变成了regexec(®ex, av[1], 2, pmatch, 0);
谢谢 :)
[%2u-%2u]
should be[%2llu-%2llu]
to avoid warningformat specifies type 'unsigned int' but the argument has type 'regoff_t' (aka 'long long')
- coterobarros