Chinaunix首页 | 论坛 | 博客
  • 博客访问: 409931
  • 博文数量: 54
  • 博客积分: 1186
  • 博客等级: 少尉
  • 技术积分: 668
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 04:57
文章分类

全部博文(54)

文章存档

2013年(1)

2012年(6)

2011年(47)

我的朋友

分类: C/C++

2011-05-18 10:53:47

#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

阅读(3792) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~