我正在尝试使用正则表达式从另一个字符串中提取字符串。
我正在使用 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);
谢谢:)
最佳答案
这是一个演示捕获多个组的代码示例。
您可以看到组“0”是整个匹配项,后续组是括号内的部分。
请注意,这只会捕获源字符串中的第一个匹配项。 Here's a version that captures multiple groups in multiple matches。
#include <stdio.h>
#include <string.h>
#include <regex.h>
int main ()
{
char * source = "___ abc123def ___ ghi456 ___";
char * regexString = "[a-z]*([0-9]+)([a-z]*)";
size_t maxGroups = 3;
regex_t regexCompiled;
regmatch_t groupArray[maxGroups];
if (regcomp(®exCompiled, regexString, REG_EXTENDED))
{
printf("Could not compile regular expression.\n");
return 1;
};
if (regexec(®exCompiled, source, maxGroups, groupArray, 0) == 0)
{
unsigned int g = 0;
for (g = 0; g < maxGroups; g++)
{
if (groupArray[g].rm_so == (size_t)-1)
break; // No more groups
char sourceCopy[strlen(source) + 1];
strcpy(sourceCopy, source);
sourceCopy[groupArray[g].rm_eo] = 0;
printf("Group %u: [%2u-%2u]: %s\n",
g, groupArray[g].rm_so, groupArray[g].rm_eo,
sourceCopy + groupArray[g].rm_so);
}
}
regfree(®exCompiled);
return 0;
}
输出:
Group 0: [ 4-13]: abc123def
Group 1: [ 7-10]: 123
Group 2: [10-13]: def
关于c - 如何使用正则表达式捕获组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55400184/