在正则表达式中匹配正斜杠

Matching forward slash in regex

我在准备正则表达式、匹配内部的正斜杠 ('/') 时遇到了麻烦。

我需要匹配 "/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(&regex, "^/.{3}[0-9]", 0);
// here checking compilation result - is OK (it means: equal 0)

/* Execute regular expression */
reti = regexec(&regex, "/ABC5", 0, NULL, 0);
// reti indicates no match!

注意:这是关于 linux (Debian) 上的 C 语言 (gcc)。当然,像 "^\/.{3}[0-9]" 这样的表达式会导致 gcc 编译警告(未知转义序列)。

解决方案: 正如@tripleee 在他的回答中所建议的那样,问题不是由斜杠引起的,而是由括号引起的:'{''}',而不是在 BRE 中允许,但在 ERE 中允许。最后我改了一行,然后一切正常。

reti = regcomp(&regex, "^/.{3}[0-9]", REG_EXTENDED);

斜线没问题,问题是 {3} 是扩展正则表达式 (ERE) 语法——您需要传递 REG_EXTENDED 或使用 \{3\}(当然在 C 字符串中,这些反斜杠需要加倍)。