in reply to Elegant way to escape a string in a regex

Problems:


It might be best to split out the replacement.

my $repl = '//div[@id="abc"]'; s/.../$repl/

The following would also work:

s{...}{ q{//div[@id="abc"]} }e
s{...}{ '//div[@id="abc"]' }e

Changed the delimiter to allow «\» to be used unescaped, and removed «\Q\E».


If you change the replacement expression's delimiter to «'», it will act as a single-quoted string literal instead of a double-quoted string literal.

s{...}'//div[@id="abc"]'

Probably best to avoid this one because it's pretty obscure.

Replies are listed 'Best First'.
Re^2: Elegant way to escape a string in a regex
by bliako (Abbot) on Apr 14, 2025 at 19:22 UTC

    Thanks. I did not know the last one you gave (s{...}'//div[@id="abc"]'). I should not have used \Q\E then. I did use it in case there were things like $1 in the replacement string. But q{//div=[@id="$1"]} gives no problem and escapes that too.

    So, just to confirm, q{} is absolutely safe for providing a substitution string which nothing in it will be interpreted by the regex (e.g. $1) or by perl (e.g @id): all contents of q{} will be literal, nothing interpreted.

      In single-quoted string literals (e.g. «q{}»), only «\» and the delimiter(s) (i.e. «{» and «}» when using «q{}») are significant. You may need to escape instances of the former, while instances of the latter needs to be escaped or balanced. Finally, you must not escape anything except the aforementioned characters.