use*_*190 8 c regex posix non-greedy
有没有办法在C中使用非贪婪的正则表达式,就像可以在Perl中使用?我尝试了几件事,但实际上并没有用.
我目前正在使用这个匹配IP地址和相应的HTTP请求的正则表达式,但它很贪婪,虽然我使用*?:
([0-9]{1,3}(\\.[0-9]{1,3}){3})(.*?)HTTP/1.1
在此示例中,它始终匹配整个字符串:
#include <regex.h>
#include <stdio.h>
int main() {
int a, i;
regex_t re;
regmatch_t pm;
char *mpages = "TEST 127.0.0.1 GET /test.php HTTP/1.1\" 404 525 \"-\" \"Mozilla/5.0 (Windows NT HTTP/1.1 TEST";
a = regcomp(&re, "([0-9]{1,3}(\\.[0-9]{1,3}){3})(.*?)HTTP/1.1", REG_EXTENDED);
if(a!=0)
printf(" -> Error: Invalid Regex");
a = regexec(&re, &mpages[0], 1, &pm, REG_EXTENDED);
if(a==0) {
for(i = pm.rm_so; i < pm.rm_eo; i++)
printf("%c", mpages[i]);
printf("\n");
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
$ ./regtest
127.0.0.1 GET /test.php HTTP/1.1"404 525" - ""Mozilla/5.0(Windows NT HTTP/1.1