in reply to how can I use regular expresion if my string to be matched has round brackets

Although the quotemeta and \Q\E answers are correct, you can also use \(\) like so:
if( m/(\()/ ) { print "I matched a paren: $1\n"; }
In fact, quotemeta and \Q\E will actually transform a string usefully (so you can see what escapes to use for next time):
print "\Qhrm, do I have to escape dots (.) and question marks?\E\n";
UPDATE: I thought quotemeta was smarter than s/(\W)/\\$1/g. count me underwhelmed. I did wonder why it was escaping spaces.

-Paul

Replies are listed 'Best First'.
Re^2: how can I use regular expresion if my string to be matched has round brackets
by JavaFan (Canon) on Oct 06, 2008 at 15:23 UTC
    In fact, quote meta and \Q\E will actually transform a string usefully (so you can see what escapes to use for next time):

    Well, quotemeta and \Q will simple escape any character that isn't a letter, digit or underscore. It doesn't have any knowledge of which characters are special and which aren't, except for the promise that if character that isn't a letter, digit or underscore is escaped, it will never carry a special meaning inside a regexp. I'm not quite sure what you mean by "useful" and "see what escapes to use for next time", but people often frown when commas, spaces and other 'harmless' punctuation characters are escaped in a regexp literal.

      quotemeta is both defined by s/(\W)/\\$1/ and by "being the function with which you escape strings in regexes", which means that in perl 5, a sequence of a backslash and a non-word-character will always literally match the non-word characters (because otherwise it would break too much existing code).

      Sadly also no non-word-character can get a new meaning without a preceding backslash, because it would also break stuff.

      So there remain only a few possible ways in which new features can be introduced syntactically:

      • With modifiers that change the syntax
      • By using one of the rare free escape sequences (\F, \T, \y, \Y)
      • By constructs that are now syntactically not valid, because they don't make any sense (perhaps ({...}), previously (* ... ))

      All of these don't quite help to clean up the syntax, though.

Re^2: how can I use regular expresion if my string to be matched has round brackets
by advait (Beadle) on Oct 06, 2008 at 15:22 UTC
    thank you all :)