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

标签 c regex linux

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

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/

相关文章:

c - 将结构实例初始化为 NULL 时出错

c - 如何更正我的程序,该程序同时具有三元运算符和按位运算符?

c - OpenMP : Parallel QuickSort

regex - 为什么 Google Cloud Builder 没有使用 gsutil rsync -x 排除文件?

.net - 如何对 TextReader 使用正则表达式?

android - 在 Android 平台上调试 Linux 内核代码

java - JavaScript 如何将未加引号的纯表达式识别为 RegExp 对象?

linux - 计算字符在 unix 中的字符串中出现的次数

python - 测试存档数据(unzip -t 等效)- Python

c - 多个以太网接口(interface) - 如何创建一个单独的网络并从 C 代码访问