regular expression: put $ in [ ]

前端 未结 3 1496
粉色の甜心
粉色の甜心 2021-01-22 08:22
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.

Can\'t

相关标签:
3条回答
  • 2021-01-22 09:11

    Notice the regular expression in the error message (after removing the marker):

    m/s[5.020000/
    

    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:

    The version + patchlevel / 1000 of the Perl interpreter.

    To prevent the variable expansion, add some escaping:

    echo "tests" | perl -pe 's/t[s\$]//g'
    

    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'
    

    or make the s optional:

    echo -e "tests\ntest" | perl -pe 's/ts?$//g'
    
    0 讨论(0)
  • 2021-01-22 09:19

    Alternatively, use sed with your expression as is:

    echo "tests"| sed "s/s[t$]//g"
    
    0 讨论(0)
  • 2021-01-22 09:21

    You have to escape the $ sign, because it is a special character:

    echo "tests"|perl -pe "s/s[t\\$]//g"
    
    0 讨论(0)
提交回复
热议问题