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

332nm8kg  于 2023-10-16  发布在  其他
关注(0)|答案(1)|浏览(125)

当使用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]);
        }
}
eyh26e7m

eyh26e7m1#

这似乎工作。

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

相关问题