当我在shell上使用它时,我正在使用正则表达式,但它不在C程序中.
有什么想法吗?
echo "abc:1234567890@werty.wer.sdfg.net" | grep -E "(\babc\b|\bdef\b):[0-9]{10}@([A-Za-z0-9].*)" //shell
reti = regcomp(®ex,"(\babc\b|\bdef\b):[0-9]{10}@([A-Za-z0-9].*)", 0); //c program
Run Code Online (Sandbox Code Playgroud)
grep -E
使用一些增强的 ERE 语法,这意味着{n,m}
量词大括号(以及(
和)
)不必转义(BRE 正则表达式中不是这种情况)。
您需要将REG_EXTENDED
标志传递给regcomp
,而且,由于您不能使用单词边界,因此将第一个替换\b
为(^|[^[:alnum:]_])
“equivalent”。您不需要尾随,因为紧随其后的模式中\b
有一个::
const char *str_regex = "(^|[^[:alnum:]_])(abc|def):[0-9]{10}@([A-Za-z0-9].*)";
Run Code Online (Sandbox Code Playgroud)
该(^|[^[:alnum:]_])
部分匹配字符串 ( ^
) 的开头或 ( |
) 字母数字或下划线以外的字符。
完整的C 演示:
#include <stdio.h>
#include <stdlib.h>
#include <regex.h>
int main (void)
{
int match;
int err;
regex_t preg;
regmatch_t pmatch[4];
size_t nmatch = 4;
const char *str_request = "abc:1234567890@werty.wer.sdfg.net";
const char *str_regex = "(^|[^[:alnum:]_])(abc|def):[0-9]{10}@([A-Za-z0-9].*)";
err = regcomp(&preg, str_regex, REG_EXTENDED);
if (err == 0)
{
match = regexec(&preg, str_request, nmatch, pmatch, 0);
nmatch = preg.re_nsub;
regfree(&preg);
if (match == 0)
{
printf("\"%.*s\"\n", pmatch[2].rm_eo - pmatch[2].rm_so, &str_request[pmatch[2].rm_so]);
printf("\"%.*s\"\n", pmatch[3].rm_eo - pmatch[3].rm_so, &str_request[pmatch[3].rm_so]);
}
else if (match == REG_NOMATCH)
{
printf("unmatch\n");
}
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)