提问人:Rusty Lemur 提问时间:9/23/2023 更新时间:9/23/2023 访问量:32
测试捕获组是否捕获了g_regex_split_simple中的某些内容的正确方法是什么
What is the proper way to test if a capturing group captured something in g_regex_split_simple
问:
使用 glib 的g_regex_split_simple时,检查捕获组是否实际捕获了任何东西的最佳方法是什么?
#include <glib.h>
#include <stdio.h>
int main() {
char *teststring = "<initiator>{address == 10.20.30.40, port == 5060, transport == UDP}</initiator>";
char **addressMatches = g_regex_split_simple("address\\s*=*\\s*(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})", teststring, 0, 0);
// What is the proper way to test here that there was a match found?
// This sort of works sometimes, but can result in segfault on some platforms if a match is not found
if (addressMatches[2]) {
printf("IP: %s\n", addressMatches[1]);
}
}
答:
0赞
Rusty Lemur
9/23/2023
#1
这似乎有效。
#include <glib.h>
#include <stdio.h>
int main() {
char *teststring = "<initiator>{address == 10.20.30.40, port == 5060, transport == UDP}</initiator>";
char **addressMatches = g_regex_split_simple("address\\s*=*\\s*(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})", teststring, 0, 0);
//The trailing text will be at index 2 if there was a match
//Otherwise index 2 will be a null pointer
//The captured text will be at index 1 if there was a match
if (addressMatches[1] != NULL && addressMatches[2] != NULL) {
printf("IP: %s\n", addressMatches[1]);
}
}
评论