正则表达式:将 $ 放入 [ ] [英] regular expression: put $ in [ ]

查看:86
本文介绍了正则表达式:将 $ 放入 [ ]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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$.如果您希望 $ 代表行尾(修剪 testtests),请使用:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆