我有以下代码:
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);
}
我想在组内获取值,这意味着跟随字符串:
some-test:56:some-other-text
我想得到56.我不知道gtk
是如何工作的,所以我在这里有点失明,我在文档中找不到任何东西。在python
我会使用groups
方法,所以在这里我需要类似的东西。你能告诉我怎么去吗?
答案 0 :(得分:1)
我在gnome.org的g-match-info-fetch page找到了有用的信息,表明g_match_info_fetch(info, 0)
会返回整个匹配项,而^ ... $
正则表达式就是整行。下面显示的代码(类似于您的代码,除了我用printf替换gtk_list_store
内容)说明g_match_info_fetch(info, 1)
返回您想要的字段。代码显示以下3行:
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
以下是代码:
#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);
}