Escaping a forward slash in a regular expression
RegexPerlEscapingRegex Problem Overview
My question is a simple one, and it is about regular expression escaping. Do you have to escape a forward slash /
in a regular expression? And how would you go about doing it?
Regex Solutions
Solution 1 - Regex
What context/language? Some languages use /
as the pattern delimiter, so yes, you need to escape it, depending on which language/context. You escape it by putting a backward slash in front of it: \/
For some languages (like PHP) you can use other characters as the delimiter and therefore you don't need to escape it. But AFAIK in all languages, the only special significance the /
has is it may be the designated pattern delimiter.
Solution 2 - Regex
Here are a few options:
-
In Perl, you can choose alternate delimiters. You're not confined to
m//
. You could choose another, such asm{}
. Then escaping isn't necessary. As a matter of fact, Damian Conway in "Perl Best Practices" asserts thatm{}
is the only alternate delimiter that ought to be used, and this is reinforced by Perl::Critic (on CPAN). While you can get away with using a variety of alternate delimiter characters,//
and{}
seem to be the clearest to decipher later on. However, if either of those choices result in too much escaping, choose whichever one lends itself best to legibility. Common examples arem(...)
,m[...]
, andm!...!
. -
In cases where you either cannot or prefer not to use alternate delimiters, you can escape the forward slashes with a backslash:
m/\/[^/]+$/
for example (using an alternate delimiter that could becomem{/[^/]+$}
, which may read more clearly). Escaping the slash with a backslash is common enough to have earned a name and a wikipedia page: Leaning Toothpick Syndrome. In regular expressions where there's just a single instance, escaping a slash might not rise to the level of being considered a hindrance to legibility, but if it starts to get out of hand, and if your language permits alternate delimiters as Perl does, that would be the preferred solution.
Solution 3 - Regex
Use the backslash \
or choose a different delimiter, ie m#.\d#
instead of /.\d/
"In Perl, you can change the / regular expression delimiter to almost any other special character if you preceed it with the letter m (for match);"
Solution 4 - Regex
If the delimiter is /, you will need to escape.
Solution 5 - Regex
If you are using C#, you do not need to escape it.
Solution 6 - Regex
For java, you don't need to.
eg: "^(.*)/\\*LOG:(\\d+)\\*/(.*)$" ==> ^(.*)/\*LOG:(\d+)\*/(.*)$
If you put \ in front of /. IDE will tell you "Redundant Character Escape "\/" in ReGex"