Issue
I've troubles with preparing regex expression, matching forward slash ('/') inside.
I need to match string like "/ABC6"
(forward slash, then any 3 characters, then exactly one digit). I tried expressions like "^/.{3}[0-9]"
, "^\/.{3}[0-9]"
, "^\\/.{3}[0-9]"
, "^\\\\/.{3}[0-9]"
- without success.
How should I do this?
My code:
#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!
NOTE: this is about C language (gcc) on linux (Debian). And of course the expression like "^\/.{3}[0-9]"
causes gcc compilation warning (unknown escape sequence).
SOLUTION: as @tripleee suggested in his answer, the problem was not caused by slash, but by brackets: '{'
and '}'
, not allowed in BRE, but allowed in ERE. Finally I changed one line, then all works OK.
reti = regcomp(®ex, "^/.{3}[0-9]", REG_EXTENDED);
Solution
The slash is fine, the problem is that {3}
is extended regular expression (ERE) syntax -- you need to pass REG_EXTENDED
or use \{3\}
instead (where of course in a C string those backslashes need to be doubled).
Answered By - tripleee Answer Checked By - Clifford M. (WPSolving Volunteer)