开发者

Regular expressions in C

I am trying to do some regular expressions matching in C and right now working on an IP addresses match.

In c# I would go with a pattern like this :

//Doesn't matter if not a correct IP, or just 4 groups of 3 digits separated string
string pattern = @"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}";

In C, with a slightly modified pattern, it doesn't seem to give any results, so I suppose there is another way of representing regular expressions to use with regcomp and regexec.

What is the correct regular expression in C to match an IP address? a reference to a good tutorial would be nice too.

Edit: this is an excerpt of my code

..
#include <regex.h>
..

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

        char* pattern = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
        reti = regcomp(&regex, pattern, 0);
        if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }

        reti = regexec(&regex, 开发者_如何转开发"21.21.12.12", 0, NULL, 0);
        if( !reti ){
                puts("Match");
        }
        else
                puts("No match");

        return 0;
}

Edit 2: The solution is to use POSIX Bracket Expressions as explained here


Instead of \d you have to use [0-9] or maybe [:digit:] and the { } syntax should be supported so the rest can be ketp, as far as I can remember. If it is not, consider using PCRE instead of the "default" regex (in this case, you don't need to change what you do in C#)


Solution: More about POSIX Bracket Expressions

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

    /*pattern to match IPv4 ip adresses*/
        char* pattern = "[[:alnum:]]{1,3}\\.[[:alnum:]]{1,3}\\.[[:alnum:]]{1,3}\\.[[:alnum:]]{1,3}";

        /* Compile regular expression */

        reti = regcomp(&regex, pattern, REG_EXTENDED);
        if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }

        /* Execute regular expression */
        reti = regexec(&regex, "2.3.4.5", 0, NULL, 0);
        if( !reti ){
                puts("Match");
        }
        else if( reti == REG_NOMATCH ){
                puts("No match");
        }
        /* Free compiled regular expression if you want to use the regex_t again */
    regfree(&regex);

        return 0;
}


You can use the below regex pattern :

string pattern = "\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b";
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜