Pine Blog

GLIB用户指南-正则表达式

1.概述

用过perl,python,shell的人在使用c语言的字符串时都会觉得c语言字符串的处理太麻烦了。很多程序测试题都会考一些字符串匹配的题。
glib

2.使用方法

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步就可以搞定

  • 创建一个GRegex,来定义你的正则表达式,这里定义了只匹配所有数字。
  • 使用g_regex_match来匹配内容中符合正则表达式规则的所有内容。
  • 因为匹配出来的是一个集合,利用g_match_info_fetch把每一项fetch出来。

文章转载自:https://blog.csdn.net/l197803/article/details/138244885?spm=1001.2101.3001.6650.2&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EYuanLiJiHua%7EPosition-2-138244885-blog-52932358.235%5Ev43%5Epc_blog_bottom_relevance_base2&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EYuanLiJiHua%7EPosition-2-138244885-blog-52932358.235%5Ev43%5Epc_blog_bottom_relevance_base2&utm_relevant_index=5,如有问题请联系删除。

未经允许不得转载:Pine Blog » GLIB用户指南-正则表达式

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

Pine Blog
Anywhere, Anytime
E-mail:59054872@qq.com
苏ICP备15059480号-1