gpt4 book ai didi

c - C中的正则表达式匹配

转载 作者:太空宇宙 更新时间:2023-11-04 02:45:38 24 4
gpt4 key购买 nike

我正在编写一个解析器来分析传入参数的内容并与正则表达式进行比较。如果找到变量结构,此解析器应返回 bool 值:

int a;

double abc;

char test;

那些变量应该匹配但不...

这是我的代码,我认为我的正则表达式是正确的..

#include "includes.h"

int check_match_var(char *str)
{
int err;
int match;
regex_t preg;
char err_buf[BUFSIZ];
const char *regex = "/^(int|char|float|double) [a-zA-Z0-9]{1,};/";

err = regcomp(&preg, regex, 0);
printf("Err : %d\n", err);
if (err == 0)
{
match = regexec(&preg, str, 0, NULL, 0);
regfree(&preg);
if (match == 0)
printf("Match !\n");
else
printf("No match !\n");
}
else
{
regerror(err, &preg, err_buf, BUFSIZ);
printf("regcomp: %s\n", err_buf);
return (1);
}
return (0);
}

int marvin(char **av)
{
check_match_var(av[1]);
return (0);
}

int main(int ac, char **av)
{
if (ac == 2)
{
marvin(av);
}
else
printf("\n");
return (0);
}

无论如何它返回 1(不匹配),我希望它返回 0(匹配)..

包含文件:

#ifndef INCLUDES_H_

#define INCLUDES_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <regex.h>
#endif

感谢帮助

最佳答案

该代码使用来自 <regex.h> 的 POSIX 正则表达式代码.您可以找到关于 regcomp() 的信息和 regexec()在线。

贴出的代码有两个问题:

  1. Paul Roub正确identified正则表达式字符串中的斜杠不是必需的。

  2. Jonathan Leffler正确identified regcomp() 处理的正则表达式和 regexec()是“基本正则表达式”或 BRE,但表示法试图使用“扩展正则表达式”或 ERE。请求 ERE 支持的方式是通过 REG_EXTENDED标记为 regcomp() 的第三个参数中的标记之一.

comment 中, user3486006确认这两个更改(并将 REG_NOSUB 添加到 regcomp() )意味着它有效。查看手册页了解什么 REG_NOSUB做;无论有没有标志,匹配都会起作用,但在这种情况下添加标志是明智的。

社区 Wiki 回答:如果 Paul 发布了回答,请采纳。

关于c - C中的正则表达式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27748999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com