我怎样才能轻松搞定正则表达式选择用C? [英] How can I easily get regex selections in C?
问题描述
我使用的 regex.h ( POSIX 的),定期EX pressions。是否有任何C选择方法的正则表达式匹配?
I'm using regex.h (POSIX) for regular expressions. Are there any selection methods for regex matches in C?
我可以很容易地检查定期EX pressions但如果我需要检索匹配的价值,我必须手动查找和存储。
I can quite easily check for regular expressions but if I need to retrieve the matched value, I have to manually find and store it.
{{( )*(([[:alnum:]]+\\.)*)?[[:alnum:]]+( )*}}
这正则表达式查找在双大括号的变量匹配。不过,我只需要在字符串中的最核心的项目。 如何可以在C检索与常规的前pressions价值?
This regex looks for any variable matches in double curly braces. But I only need the most central item in the string. How can I retrieve the value with regular expressions in C?
推荐答案
您需要的是一组 regmatch_t
S中的正则表达式可以用的指数填写传递火柴。试试下面的程序使用一个命令行参数(字符串进行测试)。
You need to pass in a set of regmatch_t
s that the regex can fill with the indices of the matches. Try the below program with a single command line argument (the string to test).
一旦有匹配的指数,它应该是很容易拔出你以后。 (注:比赛[0]
将是整个前pression的比赛,所以SUBEX pressions在开始匹配[ 1]
)
Once you have the indices of the matches, it should be fairly easy to pull out what you're after. (Note: matches[0]
will be the match of the entire expression, so the subexpressions start at matches[1]
.)
#include <stdlib.h>
#include <stdio.h>
#include <regex.h>
int main(int argc, char* argv[])
{
const char* pattern = "{{( )*(([[:alnum:]]+\\.)*)?[[:alnum:]]+( )*}}";
regex_t rex;
int rc;
if ((rc = regcomp(&rex, pattern, REG_EXTENDED))) {
fprintf(stderr, "error %d compiling regex\n", rc);
/* retrieve error here with regerror */
return -1;
}
regmatch_t* matches = malloc(sizeof(regex_t) * (rex.re_nsub + 1));
if ((rc = regexec(&rex, argv[1], rex.re_nsub + 1, matches, 0))){
printf("no match\n");
/* error or no match */
} else {
for(int i = 0; i < rex.re_nsub; ++i) {
printf("match %d from index %d to %d: ", i, matches[i].rm_so,
matches[i].rm_eo);
for(int j = matches[i].rm_so; j < matches[i].rm_eo; ++j) {
printf("%c", argv[1][j]);
}
printf("\n");
}
}
free(matches);
regfree(&rex);
return 0;
}
这篇关于我怎样才能轻松搞定正则表达式选择用C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!