Tuesday, January 27, 2009

Quoting

If you need to match strings with lots of special characters you can use quoting within regular expressions.

\Q to turn quoting on
\E to turn quoting off

(\w*)\s(\w*)\s([\Q(^%&$!/)\E]+)\s\!

He thought (%&$!/) !

The first two groups fetch the words. The third group fetches the third ,,word’’ and the rest is just one whitespace and an exclamation point.

The trick is that we do not need to escape every single character that has a special meaning.

\Q some special string \E
If you do not put the \E quoting is automatically turned off at the end of the regexp.

No comments:

Post a Comment