如何在正则表达式中使用不同的分隔符(/、|) [英] How to use different separators (/ , |) in a regular expression
问题描述
修改一个Perl 脚本,我得到了这个:
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.
所以问题是:何时以及为什么应该在正则表达式模式中使用/"或|"还是,"?
推荐答案
在 Perl 中,在替换操作符,以及许多其他操作符中,您几乎可以用定界符替换任何标点符号,例如
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/\/$//
这不是那么容易阅读.
就像我上面提到的,你可以用很多运算符和函数来做到这一点:
Like I mentioned above, you can do this with a great many operators and functions:
m#...#
qw/.../
qw#...#
tr;...;;
qq?...?
这篇关于如何在正则表达式中使用不同的分隔符(/、|)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!