在C中过滤字符串

时间:2010-03-11 05:28:01

标签: c regex string

如何在c中过滤字符串?我想删除任何不是[a-z0-9_]的内容。

int main(int argc, char ** argv) {
   char* name = argv[1];
   // remove anything that isn't [a-z0-9_]

   printf("%s", name);
}

6 个答案:

答案 0 :(得分:1)

char *src, *dst;
for (src = name, dst = name; *src; src++) {
   if ('a' <= *src && *src <= 'z' 
    || '0' <= *src && *src <= '9' 
    || *src == '_') *dst++ = *src;
}
*dst = '\0';

编辑:多个小修订版。我希望现在能搞清楚。

答案 1 :(得分:1)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, char ** argv)
{    
    char *name, *inp, *outp;

    if (argc < 2)
    {
        fprintf(stderr, "Insufficient arguments.\n");
        return 1;
    }

    inp = argv[1];
    name = malloc(strlen(inp) + 1);
    outp = name;

    if (!name)
    {
        fprintf(stderr, "Out of memory.\n");
        return 2;
    }

    while (*inp)
    {
        if (islower((unsigned char)*inp) || isdigit((unsigned char)*inp) || *inp == '_')
            *outp++ = *inp;
        inp++;
    }

    *outp = '\0';

    puts(name);
    free(name);

    return 0;
}

答案 2 :(得分:1)

如果你只想从第一个参数中删除那些不需要的字符,就不需要内存分配,只需逐个字符地浏览输入字符串。而且,如果您知道您将在ASCII环境(或任何其他支持连续az)的工作中工作,您甚至可以用更快的版本检查字符范围来替换函数调用。 / p>

但是,我无法看到速度的提升足以证明非便携式代码的合理性。

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, char ** argv) {
    int i;
    char *p;
    if (argc > 1) {
        for (p = argv[1]; *p != '\0'; p++) {
           if (islower(*p) || isdigit(*p) || *p == '_') {
               putchar (*p);
           }
        }
        putchar ('\n');
    }
    return 0;
}

答案 3 :(得分:0)

C标准库不提供对正则表达式的任何支持 您需要在C中下载一个RegEx库(一个非常常见的是PCRE),或者在循环中执行此操作(在手头的情况下更容易,因为所寻求的表达式都是单个字符,因此没有回溯)。

循环方法看起来像:

int main(int argc, char ** argv) {
   char* name = argv[1];

   // remove anything that isn't [a-z0-9_]
   char strippedName[200];
   int iIn, iOut;  // subscript in Name and StrippedName respectively

   iIn = iOut = 0;
   while (name[iIn] != '\0' && iOut < (sizeof(strippedName) + 1)) {
      // some condition defining a desirable character
      // BTW, this condition should actually be
      //    if (islower(name[iIn]) || isdigit(name[iIn] || name[iIn] == '_')
      // to match the OP's requirement exactly 
      if (isalnum(name[iIn]) || name[iIn] == '_')
         strippedName[iOut++] = name[iIn];
      iIn++;
   }
   strippedName[iOut++] = '\0';

   printf("%s", strippedName);
}

C语言中的其他正则表达式(前面提到的PCRE除外):

答案 4 :(得分:0)

查看isalphanum

答案 5 :(得分:0)

检查ctype是否有函数来测试循环中的每个字符。