c - | (或者C语言中的正则表达式中运算符不起作用)

标签 c regex

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(&regex, "1 | 2c | 3c", REG_EXTENDED);
    if( reti ){ fprintf(stderr, "Could not compile regex\n"); return(1); }

    /* Execute regular expression */
    reti = regexec(&regex, "123", 0, NULL, 0);
    if( !reti ){
            puts("Match");
    }
    else if( reti == REG_NOMATCH ){
            puts("No match");
    }
    else{
            regerror(reti, &regex, 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(&regex);

    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例如 12c3c

关于c - | (或者C语言中的正则表达式中运算符不起作用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30639866/

相关文章:

c# - RegEx 替换美元符号之间的文本

线程并发

c - 二叉搜索树内存错误

c - 确保读取整个结构

regex - hh :mm:ss format in TextFormField or TextField without using pickers 中的 Flutter 输入时间

python - 为什么惰性匹配在此正则表达式中不起作用?

C:如何得到一个4096位的质数?

C 转换 double ->long -> Short (使用右移 ">>")

具有两个或多个符号的 Java 正则表达式问题

c++ - 使用 regex_* 解析/etc/passwd,非标准行为 C++