Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use different separators (/ , |) in a regular expression

Modifying a Perl script, i got this:

$var =~ s,/$,,;

it seems to be a regex pattern, but i was expecting to found "/" (or "|") instead of "," as separator.

So the question is: when and why one should use in a regex pattern "/" or "|" or ","?

like image 797
Filippo Lauria Avatar asked Jan 24 '14 14:01

Filippo Lauria


1 Answers

In Perl, in the substitution operator, as well as many other operators, you can substitute the delimiter for almost any punctuation character, such as

s#/$##
s=/$==
s!/$!!

Which one to use when is a matter of what you need at the time. Preferably you choose a delimiter that does not conflict with the characters in your regex, and one that is readable.

In your case, a different delimiter from / was used because one wanted to include a slash in the regex, to remove a trailing slash. With the default delimiters, it would have been:

s/\/$//

Which is not as easy to read.

Like I mentioned above, you can do this with a great many operators and functions:

m#...#
qw/.../
qw#...#
tr;...;;
qq?...?
like image 50
TLP Avatar answered Sep 21 '22 01:09

TLP