How to escape dollar sign ($) in a string using perl regex

前端 未结 3 1389
青春惊慌失措
青春惊慌失措 2020-12-02 01:53

I\'m trying to escape several special characters in a given string using perl regex. It works fine for all characters except for the dollar sign. I tried the following:

3条回答
  •  [愿得一人]
    2020-12-02 02:27

    $ has special meaning in regexp, namely "end of string". You would be better off with something like this:

    # escape special characters, join them into a single line
    my $chars = join '', map { "\\$_" } keys %special_characters;
    $string =~ s/([$chars])/$special_characters{$1}/g;
    

    Also, perl doesn't like "$" much, better use '$' (single quotes => no interpolation).

    UPDATE: Sorry, I was writing this in a hurry => too many edits :(

提交回复
热议问题