开发者

Regular Expression in C

I'm trying to match a string "123,1234" using regex.h. Following pattern does the job:

"^[0-9]\{1,\},[0-9]\{1,\}$"

If I'm giving it as a commandline argument it works fine. But when I use it inside C code it does not work. Probably because identifying backward slashes as escape characters.

Sample Code:

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

int main (int argc, char * argv[]){
    regex_t regex;
    int reti;
    char msgbuf[100];
    char * string, * pattern;

    string = "123,1234";
    pattern = "^[0-9]\{1,\},[0-9]\{1,\}$";

    if(regcomp(&regex, pattern, 0))
    {
            fprintf(stderr, "Could not compile regex\n");
            exit(107);
    }

    if(!(reti = regexec(&regex, string, 0, NULL, 0)))
    {
            printf("MATCH\n");
    }
    else if(reti == REG_NOMATCH)
    {
            printf("NO MATCH\n");
    }
    else
    {
            regerror(reti, &regex, msgbuf, sizeof(msgbuf));
            fprintf(stderr, "Regex match failed: %s\n", msgbuf);
            exit(107);开发者_如何学编程
    }

    regfree(&regex);

    return 0;
}

How can I solve this?


Your regular expression is an ERE not a BRE, so you need to pass the REG_EXTENDED flag to regcomp. Then, as others have said, remove the backslashes too.


^[0-9]{1,},[0-9]{1,}$ Take out the \ backslashes. They escape the character immediately following.


To override the slash as an escape sequence, in C one uses a slash to escape a slash, so \ becomes \\.

However, since you are not passing the string to the command line, the curly braces { and } are not going to be caught by the shell's parser, so you could just try it without all of the slashes.

"^[0-9]{1,},[0-9]{1,}$"


If the slashes are being treated as escape characters, have you tried doubling up the slashes so that they are treated as escaped slashes?

ie

"^[0-9]\\{1,\\},[0-9]\\{1,\\}$"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜