【发布时间】:2020-01-02 12:46:32
【问题描述】:
我在准备正则表达式、匹配正斜杠 ('/') 时遇到了麻烦。
我需要匹配 "/ABC6" 之类的字符串(正斜杠,然后是任意 3 个字符,然后是一个数字)。我尝试了"^/.{3}[0-9]"、"^\/.{3}[0-9]"、"^\\/.{3}[0-9]"、"^\\\\/.{3}[0-9]" 之类的表达式 - 没有成功。
我该怎么做?
我的代码:
#include <regex.h>
regex_t regex;
int reti;
/* Compile regular expression */
reti = regcomp(®ex, "^/.{3}[0-9]", 0);
// here checking compilation result - is OK (it means: equal 0)
/* Execute regular expression */
reti = regexec(®ex, "/ABC5", 0, NULL, 0);
// reti indicates no match!
注意:这是关于 linux (Debian) 上的 C 语言 (gcc)。当然,"^\/.{3}[0-9]" 这样的表达式会导致 gcc 编译警告(未知转义序列)。
解决方案: 正如@tripleee 在他的回答中所建议的那样,问题不是由斜杠引起的,而是由括号引起的:'{' 和 '}',在 BRE 中不允许,但在 ERE 中允许。最后我改了一行,然后一切正常。
reti = regcomp(®ex, "^/.{3}[0-9]", REG_EXTENDED);
【问题讨论】: