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(®ex, pattern, 0);
if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }
reti = regexec(®ex, 开发者_如何转开发"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(®ex, pattern, REG_EXTENDED);
if( reti ){ fprintf(stderr, "Could not compile regex\n"); exit(1); }
/* Execute regular expression */
reti = regexec(®ex, "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(®ex);
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";
精彩评论