regular expression: put $ in [ ]

前端 未结 3 1531
粉色の甜心
粉色の甜心 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'
    

提交回复
热议问题