The backslash is the simplest character in regular expressions.
It’s used to turn regular expressions characters into normal characters. I have also heard this described as ‘escaping’ the regex if you want to get fancy about it. To achieve this, all you have to do is precede any special character you want to treat as a normal character with a backslash. Read on for some examples of how to do
it and where and when it’s useful.
There are a number of reasons why you might want to escape regex when using google analytics. There are a number of characters that are special in regular expressions that are all too ordinary in your google analytics reports! We have already come across some of them in the course of this series of posts.
Particularly in the content reporting, you will see a lot of question marks knocking around. Although I overwrite it, the default setting on this blog names all my pages with numerical ids like ‘?p=123’. Many sites have products, categories, and other content reliant on query strings, and we need to report on them.
The full stop is another special character in regex that pops up in URLs from time to time and may cause you a few problems.
Lets say you want to filter in google analytics for ‘yoursite.com/products.aspx?p=123’
Google Analytics will match two things:
The regex will match this because the question mark has stripped out the ‘x’ and the question mark itself is disregarded.
The regex will match this because the question mark makes the ‘x’ optional, so it’s still there in this match, but the question mark is disregarded.
We need to use the backslash to make all those dots and question marks normal characters, and we do this simply by placing a backslash in front of them like this:
So when you want a regular expression to behave like a plain character, use
TIP: Despite the fact that full stops, or dots, don’t generally cause problems when not preceded by a backslash, I strongly advise you to use the backslash anyway. It’s possible that it could cause mismatches in the wrong circumstances. It costs a second of your life and ensures that you’re matching exactly what you think you’re matching.
Links to the rest of the series:
RegEx 1: Introduction
RegEx 2: Pipe
RegEx 3: Brackets
RegEx 4: Question Mark
RegEx 5: Backslash – You are here!
RegEx 6: Plus Sign
RegEx 7: Dot
RegEx 8: Star
RegEx 9: Dot Star
RegEx 10: Caret
RegEx 11: Dollar Sign
RegEx 12: Square Brackets
RegEx 13: 5 Great Places to use RegEx