gtk, regexp: how to get groups value
I have following code:
gchar **split = g_strsplit(str, "\n", 0);
gchar **pointer = NULL;
GRegex *line_regex = NULL;
GMatchInfo *info = NULL;
line_regex = g_regex_new("^.*:(\\d+):.*$", 0, 0, NULL);
gtk_list_store_clear(store);
gtk_list_store_clear(store);
for (pointer = split; *pointer; pointer++)
if (strlen(*pointer)){
gchar *word = "";
if (line_regex && g_regex_match(line_regex, *pointer, 0, &info)){
if (g_match_info_matches(info)){
word = g_match_info_fetch(info, 0);
}
}
gtk_list_store_insert_with_values(store, NULL, -1, 0, word, 1, *pointer, -1);
}
I开发者_运维技巧 would like to get value inside the group, which means for following string:
some-test:56:some-other-text
I would like to get 56. I have no idea how gtk
works, so I am a little blind here and I haven't found anything in docs. In python
I would use groups
methods, so here I would need something similar. Could you advise me how to get it?
I found useful information at gnome.org's g-match-info-fetch page which indicates that g_match_info_fetch(info, 0)
returns the whole match, which for your ^ ... $
regex is the whole line. The code shown below (which is like your code, except I replaced gtk_list_store
stuff with a printf) illustrates that g_match_info_fetch(info, 1)
returns the field you want. The code displays the following 3 lines:
info 1 = 56, info 0 = a-test:56:some-other-text
No match in b-test:283B:some-other-text
info 1 = 718, info 0 = c-test:718:some-other-text
Here's the code:
#include <string.h>
#include <gtk/gtk.h>
int main(void) {
char *str = "a-test:56:some-other-text\nb-test:283B:some-other-text\nc-test:718:some-other-text\n";
gchar **split = g_strsplit(str, "\n", 0);
gchar **pointer = NULL;
GRegex *line_regex = NULL;
GMatchInfo *info = NULL;
line_regex = g_regex_new("^.*:(\\d+):.*$", 0, 0, NULL);
for (pointer = split; *pointer; pointer++)
if (strlen(*pointer)) {
if (line_regex && g_regex_match(line_regex, *pointer, 0, &info)) {
if (g_match_info_matches(info)) {
printf ("info 1 = %4s, info 0 = %s\n",
g_match_info_fetch(info, 1),
g_match_info_fetch(info, 0));
}
} else
printf ("No match in %s\n", *pointer);
}
return (0);
}
精彩评论