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?
问题:
回答1:
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.
回答2:
In Perl, you can choose alternate delimiters. You're not confined to m//
. You could choose another, such as m{}
. Then escaping isn't necessary. As a matter of fact, Damian Conway in "Perl Best Practices" asserts that m{}
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 are m(...)
, m[...]
, and m!...!
.
回答3:
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);"
回答4:
If the delimiter is /, you will need to escape.