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

倾然丶 夕夏残阳落幕 提交于 2020-04-15 08:08:04

问题


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 ","?


回答1:


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?...?



回答2:


In Perl, the default regular expression delimiter is /.

However, other characters may be used instead of /. Typically, you would use alternate delimiters when the regular expression itself includes a /. Using alternate delimiters avoids excessive escaping of the delimiter:

s/foo\/bar\//baz/;

vs.

s|foo/bar/|baz|;

perlpdoc perlop:

This is particularly useful for matching path names that contain "/", to avoid LTS (leaning toothpick syndrome).



来源:https://stackoverflow.com/questions/21335765/how-to-use-different-separators-in-a-regular-expression

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!