Tech Notes

Regular Expressions Useful for Google Analytics

Regular expressions for Google Analytics goals: require a string in the URL, exclude a string, or both at once.

In Google Analytics, you sometimes need to set up a goal that requires a particular string in the URL, or one that excludes URLs containing a particular string. You can set up these goals using regular expression URL matching with the expressions below. The examples use PHP’s preg_match to show what each expression matches.

1. To require a string in the URL, use this regular expression:

preg_match("/^(?=.*?\bmatching\b).*$/", "http://tech.sarathdr.com/matching", $matches );
echo $matches[0];
// Outputs http://tech.sarathdr.com/matching

2. To match only URLs that don’t contain the string:

preg_match("/^((?!matching).)*$/", "http://tech.sarathdr.com/matching", $matches );
echo $matches[0];
// Outputs nothing

3. To do both in a single regular expression:

preg_match("/^(?=.*?\bmatching\b)((?!avoid_this).)*$/", "http://tech.sarathdr.com/matching/avoid_this", $matches );
echo $matches[0];
// Outputs nothing
preg_match("/^(?=.*?\bmatching\b)((?!avoid_this).)*$/", "http://tech.sarathdr.com/matching/", $matches );
echo $matches[0];
// Outputs http://tech.sarathdr.com/matching/