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
或 $
?
最佳答案
注意错误消息中的正则表达式(删除标记后):
m/s[5.020000/
这为我们提供了有关正在发生的事情的线索。在评估正则表达式之前,$]
被替换为 5.020000
。引用man perlvar
,我们可以看到$]
是一个特殊的变量:
The version + patchlevel / 1000 of the Perl interpreter.
为了防止变量扩展,添加一些转义:
echo "tests" | perl -pe 's/t[s\$]//g'
这将删除 ts
或文字 t$
。如果您希望 $
代表行尾(修剪 test
和 tests
),请使用:
echo -e "tests\ntest" | perl -pe 's/t(s|$)//g'
或者使 s
可选:
echo -e "tests\ntest" | perl -pe 's/ts?$//g'
关于regex - 正则表达式 : put $ in [ ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26399332/