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

I would not use regex for replacing fixed strings like this but rather substr. That means that this problem of avoiding interpolation etc. just vanishes. As a bonus it should usually be faster too.


🦛

  • Comment on Re: Elegant way to escape a string in a regex

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

    good idea, it suits me fine and eliminates all problems, thanks.

      If you use fixed templates, maybe consider sprintf or - depending on the number of templates - just variable interpolation.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      see Wikisyntax for the Monastery

Re^2: Elegant way to escape a string in a regex
by Anonymous Monk on Apr 15, 2025 at 19:44 UTC

    The only way I can think of is with using index() to find the position of the string to replace:

    my $template = 'aaa <%xx%> bbb'; my $repl = substr $template, index($template, '<%xx%>'), length('<%xx% +>'), '//div[@id="abc"]'; print $template; # aaa //div[@id="abc"] bbb