c - Linux C LibPCRE 输出独特的结果

标签 c regex pcre

我有以下代码匹配包含多个重复项的字符串中的 REGEX,我想做的是仅打印出唯一匹配项,我该怎么办?添加到数组而不是使其唯一然后才打印出结果?谢谢!

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pcre.h>

int main() {
  pcre *myregexp;
  const char *error;
  int erroroffset;
  int offsetcount;
  int offsets[(0+1)*3]; // (max_capturing_groups+1)*3
  const char *result;
  char *subject = "9,5,3,2,5,6,3,2,5,6,3,2,2,2,5,0,5,5,6,6,1,";
  myregexp = pcre_compile("\\d,", PCRE_MULTILINE|PCRE_DOTALL|PCRE_NEWLINE_ANYCRLF, &error, &erroroffset, NULL);

  if (myregexp != NULL) {
    offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), 0, 0, offsets, (0+1)*3);

    while (offsetcount > 0) {

      if (pcre_get_substring(subject, offsets, offsetcount, 0, &result) >= 0) {
        printf("%s\n", result);
      }

      offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), offsets[1], 0, offsets, (0+1)*3);
    }

  } else {
      printf("Syntax error in REGEX at erroroffset\n");
  }

}

这个输出:

bash$ ./regex
9,
5,
3,
2,
5,
6,
3,
2,
5,
6,
3,
2,
2,
2,
5,
0,
5,
5,
6,
6,
1,

我需要:

bash$ ./regex
0,
1,
2,
3,
5,
6,
9,

最佳答案

是的,添加到数组并从那里删除重复数据。

您不能使用正则表达式搜索唯一值。您可以使用正则表达式搜索替换并删除重复的内容,例如双换行、多个空格等,但是当需要使用随机搜索进行重复删除时,这不起作用。

这是一个如何重复数据删除的例子:a -> b

#include <stdio.h>
#include <string.h>    
main()
{
    char *a[5];
    int a_len = 5;

    a[0] = "a";
    a[1] = "b";
    a[2] = "b";
    a[3] = "a";
    a[4] = "c";

    char *b[a_len];
    int b_len = 0;

    int already_exists;
    int i, j;
    for (i = 0; i < a_len; i++) 
    {
        already_exists = 0;
        for ( j = 0; j < b_len; j++)
        {
            if (!strcmp(a[i], b[j]))
            {
                already_exists = 1;
                break;
            }
        }

        if (!already_exists)
        {
            b[b_len] = a[i];
            b_len++;
        }
    }

    for (i = 0; i < b_len; i++) 
    {
        printf("%s", b[i]);
    }
}

对于这些小数组,这可能是最快的算法。为了在更大的阵列上获得更好的性能,我建议对排序的阵列进行重复数据删除。

关于c - Linux C LibPCRE 输出独特的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21649423/

相关文章:

c++ - 在 C 中转换 vector 的 C++ 实现

javascript - 带有特殊字符 (.) 的正则表达式字边界 javascript

c++ - 如何编写 boost::spirit::qi 解析器来执行 '?' 在正则表达式中所做的事情?

ios - ORKTextAnswerFormat 正则表达式验证

python - Python中的Perl兼容正则表达式(PCRE)

php - PCRE 在没有 UTF 支持的情况下编译

c - ‘DisplayMenu’ 的静态声明遵循非静态声明

c - 在 visual studio 的命令行中以 C 的形式作为标准输入文件

c++ - 在 openCv 中同时使用 2 个网络摄像头

$ request_uri中的nginx : rewrite rule to remove/index. html