不熟悉在 C 语言上使用正则表达式库。目前正在尝试使用Regexec() 和 Regcomp()函数来搜索与我的模式或正则表达式匹配的字符串。但我不能* t 生成我匹配的字符串。我是否遗漏了代码中的某些内容,或者函数的任何错误用法?
我的示例代码:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <regex.h>
int main(int argc, char ** argv)
{
regex_t r;
const char * my_regex = "(\\d+.\\d+.\\d+.\\d+)";
const char * my_string = "Am trying to match any ip like, 23.54.67.89 , in this string and 123.232.123.33 is possible";
const int no_of_matches = 10;
regmatch_t m[no_of_matches];
printf ("Trying to match '%s' in '%s'\n", my_regex, my_string);
int status = regcomp (&r, my_regex, REG_EXTENDED|REG_NEWLINE);
printf("status: %d\n",status);
if(status!=0)
{
printf ("Regex error compiling \n");
}
int match_size = regexec (&r, my_string, no_of_matches, m, 0);
printf("Number of Matches : %d\n",match_size);
int i = 0;
for (i = 0; i < match_size; i++)
{
//Now i wana print all matches here,
int start = m[i].rm_so;
int finish = m[i].rm_eo;
printf("%.*s\n", (finish - start), my_string + start);
}
regfree (& r);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在这里,问题是:我不能*打印我的比赛。有什么建议吗?我在 linux 上。我已经编辑了我的 for 循环,现在它打印:
Trying to match '(\d+.\d+.\d+.\d+)' in 'Am trying to match any ip like, 23.54.67.89 , in this string and 123.232.123.33 is possible'
status: 0
Number of Matches : 1
m trying to match any ip like, 23.54.67.89 , in this string and 123.232.123.33 is possible
Run Code Online (Sandbox Code Playgroud)
但我期待我的输出为:
Trying to match '(\d+.\d+.\d+.\d+)' in 'Am trying to match any ip like, 23.54.67.89 , in this string and 123.232.123.33 is possible'
status: 0
Number of Matches : 2
23.54.67.89
123.232.123.33
Run Code Online (Sandbox Code Playgroud)
您的正则表达式不是 POSIX 正则表达式。您正在使用 Perl/Tcl/Vim 风格,这不会像您希望的那样工作。
regcomp()和regexec()是POSIX 正则表达式,因此,是符合 POSIX 标准(或只是 POSIX-y)C 库的一部分。它们不仅仅是某些正则表达式库的一部分;这些是 POSIX 标准的东西。
特别是,POSIX 正则表达式不识别\d,或任何其他反斜杠字符类。你应该[[:digit:]]改用。(字符类括在方括号中,因此要匹配您可以使用的任何数字或小写字母[[:digit:][:lower:]]。对于除控制字符以外的任何内容,您都可以使用[^[:cntrl:]]。)
通常,您可以查看正则表达式维基百科文章中的字符类表,其中包含对等价类的简明摘要和说明。
您是否需要一个支持区域设置的示例来演示这一点?