Thursday, 20 November 2008

6: Escaping the metacharacter

So: the obvious question. The question is 'but if I write a regular expression for some text, and there's a question mark in it, and it really means 'this is the end of the sentence and the sentence is a question', what do I do?'

Easy peasy. If the symbol has a special meaning that you don't want to use, you need to escape the special meaning. To do this, you use a metacharacter. 

Every time you mean to use a symbol as a character (i.e. not a metacharacter), you use this: \

So if you had this piece of text:

What is wrong with this damn computer?

And you wanted the ? to mean (the way it usually does) 'this is the end of the sentence and the sentence is a question', you would start your regex like this: 

find: What is wrong with this damn computer\?

The means 'literally'. It means 'this is not a metacharacter, it's just a nice normal character. I use at least once in every regex I ever write.

Warning: sometimes \ reverses, and indicates that the next character is, in fact, special (I know, it's confusing) The most frequently used examples of this are \n and \t\n means 'new line', and \t means 'tab'. More on these two in lesson seven.
 

No comments:

Post a Comment