正则表达式:将 $ 放入 [ ] [英] regular expression: put $ in [ ]
问题描述
echo "tests"|perl -pe "s/s[t$]//g"
Unmatched [ in regex; marked by <-- HERE in m/s[ <-- HERE 5.020000/ at -e line 1, <> line 1.
我不能把 $
放在 [ ]
中吗?为什么?有没有其他方法可以匹配 t
或 $
?
Can't I put $
in [ ]
? Why? Is there any another method to match t
or $
?
推荐答案
注意错误信息中的正则表达式(去掉标记后):
Notice the regular expression in the error message (after removing the marker):
m/s[5.020000/
这为我们提供了有关正在发生的事情的线索.在评估正则表达式之前,$]
被替换为 5.020000
.参考 man perlvar
,我们可以看到$]
是一个特殊的变量:
This gives us a clue about what is happening. The $]
was replaced with 5.020000
before the regex was evaluated. Referring to man perlvar
, we can see that $]
is a special variable:
Perl 解释器的版本 + 补丁级别/1000.
The version + patchlevel / 1000 of the Perl interpreter.
为了防止变量扩展,添加一些转义:
To prevent the variable expansion, add some escaping:
echo "tests" | perl -pe 's/t[s\$]//g'
这将删除 ts
或文字 t$
.如果您希望 $
代表行尾(修剪 test
和 tests
),请使用:
This will remove ts
or literal t$
. If you want the $
to represent the end of the line (to trim both test
and tests
), use:
echo -e "tests\ntest" | perl -pe 's/t(s|$)//g'
或将 s
设为可选:
echo -e "tests\ntest" | perl -pe 's/ts?$//g'
这篇关于正则表达式:将 $ 放入 [ ]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!