测试捕获组是否捕获了g_regex_split_simple中的某些内容的正确方法是什么

What is the proper way to test if a capturing group captured something in g_regex_split_simple

提问人:Rusty Lemur 提问时间:9/23/2023 更新时间:9/23/2023 访问量:32

问:

使用 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]);
        }
}
c 正则表达式 glib

评论

0赞 Shawn 9/23/2023
为什么使用拆分函数而不是匹配函数?
0赞 Rusty Lemur 9/23/2023
match 函数是否只返回布尔值?是否可以从匹配函数中获取捕获组?
0赞 Rusty Lemur 9/23/2023
我能找到的关于匹配函数的最佳文档在这里:lzone.de/examples/Glib%20GRegex。但它看起来比我下面回答中的拆分函数要复杂得多。

答:

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]);
       }
}