我在 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/