首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Linux输出唯一的结果

问Linux输出唯一的结果
EN

Stack Overflow用户
提问于 2014-02-08 17:35:49
回答 1查看 325关注 0票数 1

下面的代码与包含多个副本的字符串中的REGEX匹配,我要做的是只打印出唯一的匹配项,我能做什么?添加到数组比使其唯一,然后打印出来的结果?谢谢!

代码语言:javascript
复制
#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");
  }

}

这一产出如下:

代码语言:javascript
复制
bash$ ./regex
9,
5,
3,
2,
5,
6,
3,
2,
5,
6,
3,
2,
2,
2,
5,
0,
5,
5,
6,
6,
1,

我需要:

代码语言:javascript
复制
bash$ ./regex
0,
1,
2,
3,
5,
6,
9,
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-02-08 17:50:23

是的,添加到数组并从那里去重复。

不能使用regex搜索唯一值。您可以使用regex搜索替换和去重复一些东西,比如双新行、多个空格等等,但是当需要使用随机搜索进行去重复时,这是行不通的。

下面是如何使用deduplicate: a -> b的示例

代码语言:javascript
复制
#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]);
    }
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21649423

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档