Regex in Google Ads script

Photo by Nathana Rebouças on Unsplash

For non-member, you may read the full article in this link.

Hey, fellow digital marketers! If you’re already dabbling in Google Ads Scripts to automate and supercharge your campaigns, there’s a powerful tool you might be underutilizing: Regular Expressions (Regex).

Think of Regex as a secret code for text. It’s a sequence of characters that defines a search pattern, allowing you to find, match, extract, or even replace specific pieces of text with incredible precision. When combined with the automation capabilities of Google Ads Scripts, Regex becomes a game-changer for managing complex accounts and extracting pinpoint insights.

So, why should you, a busy PPC manager or Google Ads specialist, care about learning Regex? Let’s dive in.

What Can Regex Do For Your Google Ads Scripts?

At its core, Regex in Google Ads Scripts helps you:

  • Match Patterns Like a Pro: Got specific naming conventions for your campaigns, ad groups, or even URL structures? Regex can identify them. Need to find all keywords containing digits or specific phrases? Regex is your go-to.
  • Extract Vital Information: Imagine pulling out just the brand name from a long list of campaign names, or isolating specific UTM parameters from URLs. Regex makes these surgical extractions a breeze.
  • Filter Data with Laser Focus: When you’re dealing with mountains of data, Regex allows you to create highly specific filters, ensuring your scripts only act on or report the exact information you need.

Putting Regex to Work: Practical Examples in Google Ads Scripts

The real power of Regex shines when you see it in action. While Google Ads Scripts are written in JavaScript, you’ll often use Regex within Google Ads Query Language (GAQL) to fetch entities based on specific text patterns.

Here are a few common scenarios where Regex can save you a ton of time and effort:

  1. Finding Keywords with Specific Characteristics: Let’s say you want to identify all keywords in your account that contain numerical digits (e.g., “shoes size 8” or “24 hour support”). In your GAQL query within a script, you could use a Regex pattern like '%\d%' with the LIKE operator. The \d is a shorthand character class in Regex that matches any digit.
// Example GAQL snippet within a Google Ads Script
const query = "SELECT campaign.name, ad_group.name, ad_group_criterion.keyword.text " +
"FROM keyword_view " +
"WHERE ad_group_criterion.keyword.text LIKE '%\d%'";
  1. Isolating Campaigns with a Standard Naming Convention: If you consistently name your campaigns (e.g., “Brand_Search_Winter2024_Promo”), Regex can help you select only those matching the pattern. For instance, to find campaigns ending with “_Q” followed by a digit (like “Campaign_BrandX_Q1”):
// Example GAQL snippet
const query = "SELECT campaign.name, campaign.id " +
"FROM campaign " +
"WHERE campaign.name LIKE 'Campaign\_%\_Q\d'";

Here, \_ escapes the underscore (treating it as a literal character rather than a wildcard), % acts as a wildcard for any characters, and \d again matches the quarter digit.

  1. Filtering Placement URLs by Domain: Want to check performance on specific types of websites, like educational institutions? Regex can help you filter your placement reports for URLs ending in “.edu”.
// Example GAQL snippet
const query = "SELECT detail_placement_view.target_url, metrics.impressions " +
"FROM detail_placement_view " +
"WHERE detail_placement_view.target_url LIKE '%.edu'";
  1. Extracting UTM Parameters: Need to analyze traffic based on specific utm_source tags in your destination URLs?
// Example GAQL snippet
const query = "SELECT detail_placement_view.target_url, metrics.clicks " +
"FROM detail_placement_view " +
"WHERE detail_placement_view.target_url LIKE '%utm_source=%'";

Beyond GAQL: Regex in JavaScript String Manipulation

Remember, Google Ads Scripts are JavaScript! This means you can also leverage JavaScript’s built-in Regex methods for more general text manipulation within your scripts.

  • match(): To find occurrences of a pattern in a string.
const campaignName = "My Campaign Q1 2024";
const quarterMatch = campaignName.match(/Qd/); // Finds "Q1"
if (quarterMatch) {
Logger.log(quarterMatch[0]); // Outputs: Q1
}
  • replace(): To substitute parts of a string that match a pattern.
let adDescription = "Great deals this week only!";
adDescription = adDescription.replace(/week/, "weekend");
Logger.log(adDescription); // Outputs: Great deals this weekend only!
  • test(): To check if a string matches a pattern (returns true or false).
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/;
const isValidEmail = emailPattern.test("[email protected]");
Logger.log(isValidEmail); // Outputs: true

Getting Started with Regex: Basic Building Blocks

Regex might look intimidating at first, but understanding a few core components will get you a long way:

  • Literals: Normal characters match themselves (e.g., abc matches “abc”).
  • Wildcards: The period (.) matches any single character (except newline).
  • Character Sets: Square brackets [] define a set of characters to match (e.g., [aeiou] matches any vowel). A hyphen can define a range (e.g., [0-9] for any digit, [a-z] for any lowercase letter).
  • Anchors:
  • Caret (^): Matches the beginning of a string.
  • Dollar sign ($): Matches the end of a string.
  • Quantifiers (Repetition):
  • *: Matches the preceding item 0 or more times.
  • +: Matches the preceding item 1 or more times.
  • ?: Matches the preceding item 0 or 1 time.
  • {n}: Matches exactly n times.
  • {n,}: Matches at least n times.
  • {n,m}: Matches between n and m times.
  • Escape Character: A backslash () is used to treat a special character as a literal (e.g., . matches an actual period).

It’s worth noting that Google Ads API’s GAQL uses RE2 syntax for its REGEXP_MATCH operator, which has some differences from other Regex flavors (like lacking backreferences).

The Benefits Are Clear

Incorporating Regex into your Google Ads Scripts offers:

  • Enhanced Automation: Handle complex filtering and extraction tasks programmatically that would be tedious or impossible manually.
  • Greater Flexibility: Adapt your scripts to a wider variety of account structures and naming conventions.
  • Improved Accuracy: Reduce human error by defining precise patterns for your scripts to act upon.
  • Time Savings: Automate repetitive tasks, freeing you up for more strategic work.

While there’s a learning curve, the power and flexibility Regex brings to your Google Ads Scripts are well worth the effort. Start with simple patterns, test them thoroughly (tools like Regex101.com are fantastic for this), and gradually build up your skills.

A shameless plug here. I am an advertising professional with a mission to teach others about marketing technology.

If you enjoyed this article, please do consider buying me a coffee here!

Cheers friends!

Adblock test (Why?)