正则表达式怎么写?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
int main () {
regex_t regex;
int reti;
char msgbuf[100];
const char *regIp = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){1,3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?){0,1}$";
reti = regcomp(®ex, regIp, 0);
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
printf("Regex compile: %s.", msgbuf);
reti = regexec(®ex, "192.168.100", 0, NULL, 0);
if (!reti){
puts("MUTCH!!");
} else if (reti == REG_NOMATCH) {
puts("No mutch");
} else {
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
printf("Regex match failed: %s.", msgbuf);
}
}
我没有mutch。
我尝试戴口罩,因为
^\\(?:\\(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\\)\\.\\)\\{1,3\\}\\(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\\)\\{0,1\\}$
但不再匹配。
提前致谢。
最佳答案
将 REG_EXTENDED
与 regcomp
一起使用,并在 .
之前加倍反斜杠。
将代码中的 regIp
初始化和 reti
赋值这两行替换为
const char *regIp = "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\\.){1,3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)?$";
reti = regcomp(®ex, regIp, REG_EXTENDED);
// => Regex compile: Success.MATCH!!
参见 C demo
有了 REG_EXTENDED
,模式中将允许使用 POSIX ERE 语法(这样就可以在不转义大括号的情况下使用 {m,n}
量词),并且它也将允许使用 $
。文字正则表达式转义 \
必须在 C 字符串文字中使用双反斜杠定义。
请注意,您必须将非捕获组替换为捕获 组,因为 POSIX 正则表达式不支持非捕获组。所以,所有的 (?:...)
都应该变成 (...)
。
关于c - IP 的正则表达式 c 部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47031188/