将字符串分解为C中的部分

时间:2013-07-25 20:25:55

标签: c regex

自从用C语言编写程序以来,我有一个类似下面的字符串

"VRUWFB02=I.V.R, W.F.B, plan 2, VRUWFB01=I.V.R, W.F.B, plan 1, assa=784617896.9649164, plan24, massmedua=plan12, masspedia=IVR, masojh, jhsfdkl, oijhojomn, oiafofvj, plan"

我需要在“=”之前得到那些,即VRUWFB02,VRUWFB01,assa,massmedua,masspedia。

我可以打破字符串,但无法提取这些特定字词。

任何人都可以帮助我吗

char st[] = "VRUWFB02=I.V.R, W.F.B, plan 2, VRUWFB01=I.V.R, W.F.B, plan 1,assa=784617896.9649164, plan24, massmedua=plan12, masspedia=IVR, masojh, jhsfdkl, oijhojomn, oiafofvj, plan";
char *ch;
regex_t compiled;
char pattern[80] = "  ";
printf("Split \"%s\"\n", st);
ch = strtok(st, " ");
while (ch != NULL) {
    if(regcomp(&compiled, pattern, REG_NOSUB) == 0) {
        printf("%s\n", ch);
    }
    ch = strtok(NULL, " ,");
}
return 0;

2 个答案:

答案 0 :(得分:2)

这是我用来解释事情的快速示例程序:

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

int main(void)
{
    char s[] = "VRUWFB02=I.V.R, W.F.B, plan 2, VRUWFB01=I.V.R, W.F.B, "
               "plan 1, assa=784617896.9649164, plan24, massmedua=plan12, "
               "masspedia=IVR, masojh, jhsfdkl, oijhojomn, oiafofvj, plan";
    char *p;
    char *q;

    p = strtok(s, " ");
    while (p)
    {
        q = strchr(p, '=');
        if (q)
            printf("%.*s\n", (int)(q - p), p);
        p = strtok(NULL, " ");
    }

    return 0;
}

输出:

$ ./example
VRUWFB02
VRUWFB01
assa
massmedua
masspedia

基本思想是用空格分割字符串,然后在块中查找=个字符。如果出现,请打印该块的所需部分。

答案 1 :(得分:0)

您可以使用strtok函数来破坏字符串。您可以在我参考的网页上找到使用它的示例。