c - 如何更快地检查正则表达式列表

标签 c regex algorithm

我在 C 中使用正则表达式,我正在根据正则表达式列表检查单词,下面是我所拥有的,

我有这个字符串

0118889994444  

我有这些正则表达式

^012[0-9]{10}$ if this one hits then do 1
^0011[0-9]{10}$ if this one hits then do 2
^00[0-9]{10}$ if if this one hits then do 3  
^11[0-9]{10}$ if this one hits then do 4
^011[0-9]{10}$ if this one hits then do 5 // this one will match the string

我目前正在做的是循环遍历正则表达式列表,看看哪个会命中,然后执行为该正则表达式设置的任何操作,因此,列表越大,完成循环所需的时间就越多,是否有使它更快更智能的方法或技巧:)?

最佳答案

在上面的例子中,我会完全放弃 regex,并采用一种直接的方法来检查固定列表的前缀,然后检测字符串的其余部分是否由十位数字组成.你可以这样做:

struct mathc_def {
    const char *prefix;
    int offset;
} match_defs[] = {
    {.prefix = "012",  .offset = 3}
,   {.prefix = "0011", .offset = 4}
,   {.prefix = "00",   .offset = 2}
,   {.prefix = "11",   .offset = 2}
,   {.prefix = "011",  .offset = 3}
};

bool ten_digits(const char* str) {
    int i = 0;
    while (isdigit(str[i])) {
        i++;
    }
    return i == 10;
}

char *str = "0118889994444";
for (int i = 0 ; i != 5 ; i++) {
    if (strstr(str, match_defs[i].prefix) == str && ten_digits(&str[match_defs[i].offset])) {
        printf("Item %d matched.\n", i);
    }
}

关于c - 如何更快地检查正则表达式列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20529823/

相关文章:

不能声明一个 size=var 的字符串,即使 var 是 const

C:传递二维整数数组

c - 一次读取文件而不是逐行读取文件(在 c 中)

c# - 如何为特定字符匹配 N 次后的新行?

regex - 如何用@ 替换 'at'

C 何时分配和释放内存 - 在函数调用之前,函数调用之后......等

regex - 匹配powershell正则表达式中的多个条件

Java - 有序链表算法

python素数生成

javascript - 我在 JavaScript 中执行 rot13 的哪里出错了?