Or 运算符 (|) 在 C 语言正则表达式中不起作用,它始终将输出作为 match 给出,如果我给出不正确的输入,也会将“12”或“123”或 c 显示为 MATCH。在这种情况下我会请求帮助。
#include <sys/types.h>
#include <regex.h>
#include <stdio.h>
int main(int argc, char *argv[]){ regex_t regex;
int reti;
char msgbuf[100];
/* Compile regular expression */
reti = regcomp(®ex, "1 | 2c | 3c", REG_EXTENDED);
if( reti ){ fprintf(stderr, "Could not compile regex\n"); return(1); }
/* Execute regular expression */
reti = regexec(®ex, "123", 0, NULL, 0);
if( !reti ){
puts("Match");
}
else if( reti == REG_NOMATCH ){
puts("No match");
}
else{
regerror(reti, ®ex, msgbuf, sizeof(msgbuf));
fprintf(stderr, "Regex match failed: %s\n", msgbuf);
return 1;
}
/* Free compiled regular expression if you want to use the regex_t again */
regfree(®ex);
return 0;
}
最佳答案
你的正则表达式 1 | 2c | 3c
匹配 I have 1 Dollar
中的 1
,但从您的评论中我发现您需要匹配整个字符串,而不仅仅是部分其中。为此,您需要使用 anchor ^
(字符串开头)和 $
(字符串结尾),它们仅在使用 REG_EXTENDED
标志时才起作用.
当您使用替代项时,您需要重复 anchor ,或在括号的帮助下设置一个组:
^1$|^2c$|^3c$
或者
^(1|2c|3c)$
这些表达式will safely match whole strings例如 1
、2c
或 3c
。
关于c - | (或者C语言中的正则表达式中运算符不起作用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30639866/