gpt4 book ai didi

c - 在 C 中解析正则表达式

转载 作者:太空狗 更新时间:2023-10-29 11:12:48 24 4
gpt4 key购买 nike

使用 的以下格式的正则表达式应该是什么?正则表达式。

000000|000110|12|11|alphanumeric value

6digits|6 digits|2 digits|2 digits|alphanumeric value including space

我用 (^(\\d{6})|(\\d{6})|(\\d{2})|(\\d{2})|( ([a-zA-Z0-9 ])*)$) 正则表达式,但它似乎没有按预期工作:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <regex.h>

int main()
{

int res;

char err_buf[BUFSIZ];
char src[] = "000000|000110|12|11|alphanumeric value";

const char* pattern = "(^(\\d{6})|(\\d{6})|(\\d{2})|(\\d{2})|(([a-zA-Z0-9 ])*)$)";
regex_t preg;

regmatch_t pmatch[100];

if( (res = regcomp(&preg, pattern, REG_EXTENDED)) != 0)
{
regerror(res, &preg, err_buf, BUFSIZ);
printf("regcomp: %s\n", err_buf);
exit(res);
}
// res=regcomp(&preg, src,REG_EXTENDED);
res = regexec(&preg, src, 100, pmatch, REG_NOTBOL);
//~ res = regexec(&preg, src, 10, pmatch, 0);
//~ res = regexec(&preg, src, 10, pmatch, REG_NOTEOL);

if(res == 0)
{
printf("Match Found\n");
}
else if(res == REG_NOMATCH ){
printf("NO match\n");
exit(0);
}
regfree(&preg);
return 0;
}

提前致谢。

最佳答案

因为管道是元字符并且你想匹配文字 |,你需要转义你的它们,但是如果你只使用 \| 它们它将转义它的 C++ 因此你得到的错误。像使用 \\d 一样使用 \\| 在字符串中获取文字 \d

因此你的正则表达式将是 ^(\\d{6})\\|(\\d{6})\\|(\\d{2})\\|(\\d{ 2})\\|([a-zA-Z0-9 ]*)$(我冒昧地改写了最后一组)。

正如 Jonathan 所注意到的,您正在使用不支持 \d 的 POSIX 正则表达式。如果您只想匹配 ASCII 数字,则可以使用 [0-9],如果您想要匹配更宽的字符集,则可以使用 [:digit:]。因此:

^([0-9]{6})\\|([0-9]{6})\\|([0-9]{2})\\|([0-9]{2})\\|([a-zA-Z0-9 ]*)$

关于c - 在 C 中解析正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36882070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com