Why does my Perl regex complain about "Unmatched ) in regex"?

perl, regex

Solution

If the variable $replace can contain regex meta characters you should wrap it in `\Q...\E`

\Q$replace\E

To quote Jeffrey Friedl's Mastering Regular Expressions

Literal Text Span The sequence \Q "Quotes" regex metacharacters (i.e., puts a backslash in front of them) until the end of the string, or until a \E sequence.

Problem

``` if($title =~ s/(\s|^|,|\/|;|\|)$replace(\s|$|,|\/|;|\|)//ig) ``` $title can be a set of titles ranging from President, MD, COO, CEO,... $replace can be (shareholder), (Owner) or the like. I keep getting this error. I have checked for improperly balanced '(', ')', no dice :( ``` Unmatched ) in regex; marked by <-- HERE in m/(\s|^|,|/|;|\|)Owner) <-- HERE (\s|$|,|/|;|\|)/ ``` If you could tell me what the regex does, that would be awesome. Does it strip those symbols? Thanks guys!

Original source

Related problems