holli is correct that a very straightforward way to search for text surrounded by parens, braces, brackets, etc., is to use the character class negation syntax [^...], as you want to stop capturing text to discard as soon as you find the matching parenthesis.
However, your original example has a couple of other pitfalls:
- The '$' followed by "\)" is trying to match end-of-line followed by a parenthesis, which will never succeed.
- The attempt to use the result of a match in a new regex (s/$1//) is not advisable in a couple of ways. First, you didn't actually -capture- the parenthetical expression (remember, your escaped parentheses \( ...\) are matching the open/close parentheses in the pattern, so you would need an extra set to capture those: (\(...\)); otherwise $1 won't be defined). Secondly, even if you are correctly capturing, it's not a good idea to immediately use $1 without making an assignment first, as any other regex match will change its value. Thus, it's better to write something like:
if($input =~ /^(\([^\)]*\))/)
{
my $pattern = $1;
s/$pattern//;
}
- But since you're already doing the work of searching for the pattern, why not just do the substitutition at the same time?:
if($input =~ s/^(\([^\)]*\))//)
{
# Successfully trimmed (...) at beginning of line
} else {
# Didn't match ^(...)
}
Notice that the last code segment is essentially what
holli has suggested for a regex: "if($input =~ s/^\(([^\)]+)\)\s*// )". The 2 differences are that he trims any whitespace after the final ')' with "\s*", and his expression only trims what's in the parentheses if it's one or more characters, because of the '+'. (If you want to match empty parentheses as well, use '*' instead of '+').