#include
#include
#include
#include
static void regex(const gchar *string,const gchar *reg)
{
GRegex* regex; //正则表达式对象
GMatchInfo *match_info; //匹配后的集合
GError *error = NULL;
regex = g_regex_new(reg, 0, 0, &error); //创建正则表达式
g_regex_match(regex, string, 0, &match_info); //匹配
while (g_match_info_matches(match_info)) { //利用g_match_info_fetch把每一项fetch出来
gint count = g_match_info_get_match_count( match_info );
g_print( "match count:%d\n", count );
int i;
for ( i = 0; i < count; i++ )
{
gchar* word = g_match_info_fetch(match_info, i);
printf("%d: %s\n",i,word);
g_free(word);
}
g_match_info_next(match_info, NULL);
}
g_match_info_free(match_info); //释放空间
g_regex_unref(regex);
}
int main()
{
gchar buf[1000];
gchar reg[100];
strcpy( buf, "123正则表达式456" );
strcpy( reg, "(.+?)" );
regex(buf,reg);
return 0;
}
$ gcc -lglib-2.0 test.c
$ ./a.out
match count:2
0: 123正则表达式456
1: 123正则表达式456
提示:glib中的g_print原来只能打印utf-8字符串,如果直接在g_print中写入中文,会出现如下提示。可使用g_locale_to_utf8()或g_convert函数来将字符串转换为utf-8后再用g_print打印。
[Invalid UTF-8] 0: 123\xd5\xfd\xd4\xf2\xb1\xed\xb4\xef\xca\xbd456
[Invalid UTF-8] 1: 123\xd5\xfd\xd4\xf2\xb1\xed\xb4\xef\xca\xbd456
阅读(3872) | 评论(0) | 转发(0) |