gpt4 book ai didi

c - regcomp 正确语法

转载 作者:行者123 更新时间:2023-11-30 16:12:38 26 4
gpt4 key购买 nike

我努力寻找正确的方法来让我的表达发挥作用

这是我的代码

#include <regex.h>
#include <stdio.h>

int
match(const char *string, char *pattern)
{
int status;
regex_t re;

if (regcomp(&re, pattern, REG_EXTENDED) != 0) {
printf("@@@@ error\n");
return(0); /* Report error. */
}
status = regexec(&re, string, (size_t) 0, NULL, 0);
regfree(&re);
if (status != 0) {
printf("@@@@ %d\n", status);
return(0); /* Report error. */
}
return(1);
}

int main(int argc, char **argv)
{
int ret = match(argv[1], "^[a-zA-Z0-9]*@[a-zA-Z0-9-_.]*[.]*?");

if (ret)
printf("match\n");
else
printf("not match\n");

return 0;
}

我想要实现的是检查模式 "user@host132-nd.ts"在字符串 "user@host132.nd/source_dir1" 中存在或不存在。

用户只能包含字符,主机可以包含字符和数字,也可以包含 . - _ 但字符串的开头应该以 user@host/开头

我不擅长正则表达式,但我不想编写大量循环并检查所有内容,因此使用 regexpr 的方式似乎更适合我。

我的表情是这样的: ^[a-zA-Z0-9]*@[a-zA-Z0-9-_.]*[.]*?

我查了一下using some online editors及其工作,至少它找到了 user@host 模式,但在我的代码 regcomp 中总是失败。

./a.out user@host123-nd.ts/source_dir1

@@@@ error

not match

预先感谢您的帮助。

UPDT:我检查了错误代码 regcomp并出现此错误: regcomp() failed with 'Invalid range end'

最佳答案

来自https://www.regular-expressions.info/charclass.html

The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret. Both [-x] and [x-] match an x or a hyphen. [^-x] and [^x-] match any character that is not an x or a hyphen. This works in all flavors discussed in this tutorial. Hyphens at other positions in character classes where they can't form a range may be interpreted as literals or as errors. Regex flavors are quite inconsistent about this.

你有...0-9-_。第二个连字符是导致错误的原因。打开 [ 之后或关闭 ] 之前将其移动。

关于c - regcomp 正确语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58292086/

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