字符串中的替换
我有以下字符串 ./test
我想用 test
替换它 所以,我用 perl 写了以下内容: 我的 $t =~ s/^.//;
但是,这会将 ./test
替换为 /test
任何人都可以建议我如何修复它,以便我也摆脱 /
。谢谢!
I have the following string ./test
and I want to replace it with test
so, I wrote the following in perl:my $t =~ s/^.//;
however, that replaces ./test
with /test
can anyone please suggest how I fix it so I get rid of the /
too. thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您需要转义点和斜线。
替换是
s/match/replace/
。如果删除,则为s/match//
。您想要匹配“以点和斜杠开头”,那就是^\.\/
。You need to escape the dot and the slash.
The substitution is
s/match/replace/
. If you erase, it'ss/match//
. You want to match "starts with a dot and a slash", and that's^\.\/
.该点不符合您的预期 - 它不是匹配点字符,而是匹配任何字符,因为它的特殊处理。要匹配点和正斜杠,您可以按如下方式重写表达式:
请注意,您可以随意使用不同的字符作为分隔符,以免与正则表达式中的任何此类字符混淆。
The dot doesn't do what you expect - rather than matching a dot character, it matches any character because of its special treatment. To match a dot and a forward slash, you can rewrite your expression as follows:
Note that you are free to use a different character as a delimiter, in order not to confuse it with any such characters inside the regular expression.
如果您想摆脱
./
那么您需要在正则表达式中包含这两个字符。.
和/
在此表达式中都有特殊含义(.
是一个正则表达式元字符,表示“任何字符”,而/
> 是s///
运算符的分隔符),因此我们需要通过在它们前面放置\
来转义它们。解决
/
问题的另一种(在我看来更好)方法是更改用作s///
分隔符的字符。这些都记录在 perldoc perlop 中。
If you want to get rid of
./
then you need to include both of those characters in the regex.Both
.
and/
have special meanings in this expression (.
is a regex metacharacter meaning "any character" and/
is the delimiter for thes///
operator) so we need to escape them both by putting a\
in front of them.An alternative (and, in my opinion, better) approach to the
/
issue is to change the character that you are using as thes///
delimiter.This is all documented in perldoc perlop.
您必须在点和正斜杠之前使用反斜杠:s/\.\//;
反斜杠用于编写在正则表达式中具有不同含义的符号。
You have to use a backward slash before the dot and the forward slash: s/\.\//;
The backslash is used to write symbols that otherwise would have a different meaning in the regular expression.
您需要编写
my $t =~ s/^\.\///;
(请注意,需要对句点进行转义,以便匹配文字句点而不是任何字符)。如果斜杠太多,您还可以更改分隔符,改为写入,例如my $t =~ s:^\./::;
。You need to write
my $t =~ s/^\.\///;
(Note that the period needs to be escaped in order to match a literal period rather than any character). If that's too many slashes, you can also change the delimiter, writing instead, e.g.,my $t =~ s:^\./::;
.如果你想让它匹配一个点,你需要转义点。否则它匹配任何字符。您可以选择备用分隔符——最好是在处理正斜杠时,以免在您也需要转义这些分隔符时看起来像倾斜的牙签。
You need to escape the dot if you want it to match a dot. Otherwise it matches any character. You can choose alternate delimiters --- best when dealing with forward slashes lest you get the leaning-toothpick look when you otherwise need to escape those too.
请注意,问题中的点与任何字符匹配,而不是文字“.”。
Note that the dot in your question is matching any character, not a literal '.'.
路径::类
Path::Class