How do I handle special characters in a Perl regex?

perl, regex

Solution

Try Perl's quotemeta function. Alternatively, use `\Q` and `\E` in your regex to turn off interpolation of values in the regex. See perlretut for more on `\Q` and `\E` - they may not be what you're looking for.

Problem

I'm using a Perl program to extract text from a file. I have an array of strings which I use as delimiters for the text, e.g: ``` $pat = $arr[1] . '(.*?)' . $arr[2]; if ( $src =~ /$pat/ ) { print $1; } ``` However, two of the strings in the array are `$450` and `(Buy now)`. The problem with these is that the symbols in the strings represent end-of-string and capture group in Perl regular expressions, so the text doesn't parse as I intend. Is there a way around this?

Original source