免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1379 | 回复: 0
打印 上一主题 下一主题

glib学习笔记5 使用perl正则表达式 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-12-31 00:00 |只看该作者 |倒序浏览
转载请注明出处,或联系fanyuanmail@126.com
用过perl,python,shell的人在使用c语言的字符串时都会觉得c语言字符串的处理太麻烦了。很多程序测试题都会考一些字符串匹配的题。

glib提供了一套非常好的正则表达式api,程序可以非常简单的使用c语言来做字符串的匹配。

比如一个文件 test_regex.txt
11aa222bb33333cccc44444dddddddd

要匹配出所有的数字,使用了glib库的程序
[root@localhost glib_test]# ./g_regex
11
222
33333
44444
#include glib.h>
static void print_uppercase_words(const gchar* string)
{
        GRegex* regex;
        GMatchInfo *match_info;
        GError *error = NULL;
        regex = g_regex_new("[0-9]+", 0 , 0, NULL);
        g_regex_match(regex, string, 0, &match_info);
        while (g_match_info_matches(match_info)) {
                gchar* word = g_match_info_fetch(match_info, 0);
                g_print("%s\n",word);
                g_free(word);
                g_match_info_next(match_info, NULL);
        }
        g_match_info_free(match_info);
        g_regex_unref(regex);
}
int main()
{
        char *buf;
        int length;
        g_file_get_contents("test_regex.txt", &buf, &length,NULL);
        print_uppercase_words(buf);
        return 0;
}
程序使用起来非常简单,3步就可以搞定
1.创建一个GRegex,来定义你的正则表达式,这里定义了只匹配所有数字。
2.使用g_regex_match来匹配内容中符合正则表达式规则的所有内容。
3.因为匹配出来的是一个集合,利用g_match_info_fetch把每一项fetch出来


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/58855/showart_1762911.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP