Exclude Non-Buyer Search Queries with Regex & Google Ads Scripts

Learn how to use a regex negative search query script to block non-buyer patterns, automate negative keywords in Google Ads, and eliminate wasted ad spend.

By AdTurbo Team · 2026-09-03

Managing negative keywords manually is one of the most tedious, repetitive chores in PPC management. In broad match and smart bidding environments, search queries mutate faster than standard negative match lists can catch up. An account bidding on high-intent terms like enterprise CRM software can easily burn through thousands of dollars on variations like enterprise CRM open source github repo, free enterprise CRM course pdf, or enterprise CRM login portal.

While Google Ads does not natively allow you to paste regular expressions directly into your negative keyword lists in the UI, you can execute regex filtering using Google Ads Scripts. By deploying an automated script running regular expressions against your Search Terms Report, you can dynamically identify, flag, and add negative keywords that match non-buyer intent patterns.

This guide breaks down regular expression mechanics for PPC, the syntax for lookaheads and word boundaries, practical non-buyer regex templates, and a complete, production-ready regex negative search query script you can paste directly into Google Ads.

---

Understanding Regex Mechanics in PPC Automation

Regular expressions (regex) provide a concise, declarative syntax to evaluate strings for patterns rather than literal character sequences. In Google Ads, search queries are strings of text parsed by Google's Natural Language Processing (NLP) models. While Google allows basic regex in Search Console and Google Analytics 4 reports, Google Ads Campaign Manager only accepts standard match types (broad, phrase, exact) for negative keywords.

To bridge this gap, Google Ads Scripts (which run on a Node.js / V8 JavaScript engine) allow you to fetch incoming search queries programmatically via the Google Ads Query Language (GAQL) and evaluate them against custom JavaScript RegExp patterns.

How JavaScript RegExp Interacts with Google Ads

When a Google Ads Script runs, it retrieves search terms that generated impressions or clicks within a specified timeframe (e.g., LAST7DAYS or LAST14DAYS). The script evaluates each search query string against your defined regex patterns. When a match occurs, the script pushes that string (or an extracted word from that string) into a Campaign Negative List or Ad Group Negative Keyword target.

Understanding standard regex tokens is critical before writing your exclusion logic:

• \b: Represents a word boundary. It ensures you match the standalone word and not substrings (e.g., \bfree\b matches "free software" but ignores "freelancer").

• (?: ... ): A non-capturing group. It groups characters or alternatives without saving the matched subpattern in memory, improving execution performance during script runtime.

• (\d+): Captures one or more numeric digits. This helps catch search queries containing model numbers, job codes, or academic course numbers.

• (?i): Case-insensitive flag (in standard regex engines) or i modifier in JavaScript (/pattern/i).

---

Regex Negation: Lookaheads, Lookbehinds, and Pattern Matching

In text processing, developers frequently need to find strings that do not contain certain words (negation). In PPC, however, we use regex in two distinct ways:

1. Positive Matching for Negative Identification: Identifying search terms that contain unwanted non-buyer patterns (e.g., matching any query containing free, login, jobs, diy).

2. Negative Lookaheads for Intent Filtering: Matching queries that contain a product term unless it is accompanied by a transactional modifier.

Positive vs. Negative Lookaheads in PPC Filtering

A lookahead asserts whether a specific pattern follows the current position in the string without consuming characters.

| Lookahead Type | Syntax | What It Does | PPC Application |

| :--- | :--- | :--- | :--- |

| Positive Lookahead | (?=pattern) | Matches if pattern is present ahead | Ensures a required commercial term exists before flagging |

| Negative Lookahead | (?!pattern) | Matches if pattern is NOT present ahead | Flags queries containing a brand term unless followed by "buy" or "pricing" |

| Positive Lookbehind | (?<=pattern) | Matches if pattern precedes the current text | Evaluates context preceding a keyword modifier |

| Negative Lookbehind | (?<!pattern) | Matches if pattern does NOT precede the text | Excludes matches where a negative term is part of a valid brand name |

The Mechanics of Negative Lookaheads: ^(?!.pattern).$

In programming, the classic line negation pattern is ^(?!.hede).$, which matches any string that does not contain the substring "hede". In JavaScript, this works because:

1. ^ anchors the evaluation to the beginning of the string.

2. (?!.hede) immediately looks ahead to check if "hede" appears anywhere in the line. If it does, the lookahead assertion fails, and the engine stops evaluating.

3. .$ matches the rest of the string if the negative lookahead check passes.

In Google Ads scripts, you rarely need to match the entire line to add a negative keyword. Instead, you typically run direct positive pattern matching (e.g., /(login|portal|career|salary)/i.test(query)) to isolate junk queries, or use negative lookaheads when dealing with dual-use intent terms.

javascript

// Example: Flag queries containing 'templates' UNLESS preceded by 'paid' or 'premium'

const templateRegex = /^(?!.(paid|premium)).\btemplates?\b.$/i;

console.log(templateRegex.test("free invoice templates")); // true - Flag as negative

console.log(templateRegex.test("paid invoice templates")); // false - Keep running

If manual scripting feels overwhelming or you want continuous pattern optimization without maintaining custom code, using an automated negative keyword system can eliminate manual script maintenance entirely.

---

Constructing Non-Buyer Regex Patterns by Intent Silo

Non-buyer search queries generally fall into predictable intent silos. Grouping your regex patterns by category makes it easier to test, debug, and expand your exclusion rules.

Non-Buyer Query Regex Architecture

├── Educational & Informational - \b(tutorial|how to|course|syllabus|pdf)\b

├── Employment & Careers - \b(jobs?|salary|internships?|glassdoor)\b

├── Support & Account Portals - \b(login|portal|dashboard|sign in|reset password)\b

├── Open Source & DIY - \b(diy|github|open source|freeware|cracked)\b

└── Price Sensitivity & B2C - \b(cheap|free|coupon|promo code|discount)\b

1. The Educational & Academic Pattern

Searchers looking to learn how to do something themselves rarely convert into high-ticket enterprise buyers. To catch research-oriented queries:

regex

\b(how\s+to|what\s+is|definition|meaning|tutorial|guide|course|syllabus|pdf|cheat\ssheet|slides|textbook|thesis|whitepaper\s+download)\b

2. The Employment & Career Pattern

Job hunters often search for high-volume commercial keywords followed by "vacancies" or "careers":

regex

\b(jobs?|careers?|salary|salaries|hiring|internships?|recruiting|glassdoor|indeed|work\s+at|openings|remote\s+jobs?|hourly\s+rate)\b

3. Existing User & Support Logins

If you run SaaS or service campaigns, existing users frequently click your top-of-page search ads to log in, costing you high CPCs for zero incremental value:

regex

\b(log\sin|sign\sin|portal|dashboard|sso|client\s+login|customer\s+service|support\s+phone|helpdesk|reset\s+password)\b

4. Technical / Open-Source Intent

For software companies, technical users seeking free or self-hosted alternatives can drain budgets rapidly:

regex

\b(github|open\ssource|gitlab|source\scode|repo|docker\s+image|npm|pip\s+install|api\s+docs|free\s+tier|nulled|crack(ed)?)\b

Regularly reviewing query logs using a structured search terms report guide ensures your regex libraries stay updated as search trends shift.

---

Step-by-Step: The Automated Regex Negative Script

Below is a complete, single-file Google Ads Script designed to run inside the Google Ads Scripts interface. It inspects search terms from all active Search campaigns, evaluates them against your regex non-buyer dictionary, and automatically adds matching terms as phrase match negatives to a specified Negative Keyword List.

The Complete Google Ads Script

javascript

/

• Automated Regex Non-Buyer Query Excluder

• Author: AdTurbo Engineering

• Target: Google Ads Scripts (V8 Engine)

/

const CONFIG = {

// Name of the Shared Negative Keyword List to append negatives to

negativeListName: "Automated Regex Exclusions",

// Lookback window for Search Terms (e.g., LAST7DAYS, LAST14DAYS, LAST30DAYS)

dateRange: "LAST7DAYS",

// Minimum clicks before evaluating (set to 1 to catch any spend, or 0 for impressions)

minClicks: 1,

// Set to true to log actions without actually creating negative keywords

dryRun: false,

// Regex Patterns for Non-Buyer Intent

patterns: [

/\b(how\s+to|tutorial|guide|course|syllabus|pdf|cheat\ssheet)\b/i,

/\b(jobs?|careers?|salary|salaries|hiring|internships?|glassdoor|indeed)\b/i,

/\b(log\sin|sign\sin|portal|dashboard|customer\s+service|support\s+number)\b/i,

/\b(github|open\ssource|gitlab|source\scode|docker|api\s+docs|crack(ed)?)\b/i,

/\b(free|diy|sample|torrent|nulled|open\s+source|template)\b/i

]

};

function main() {

Logger.log("Starting Regex Negative Keyword Evaluation...");

const negativeList = getOrCreateNegativeList(CONFIG.negativeListName);

const existingNegatives = getExistingNegatives(negativeList);

Logger.log(Found ${existingNegatives.size} existing negatives in list: ${CONFIG.negativeListName});

// GAQL Query to fetch search terms from active search campaigns

const query =

SELECT

searchtermview.searchterm,

metrics.clicks,

metrics.impressions,

metrics.costmicros,

campaign.id,

campaign.name

FROM searchtermview

WHERE

campaign.status = 'ENABLED'

AND campaign.advertisingchanneltype = 'SEARCH'

AND metrics.clicks = ${CONFIG.minClicks}

AND segments.date DURING ${CONFIG.dateRange}

;

const report = AdsApp.search(query);

let matchedCount = 0;

let addedCount = 0;

while (report.hasNext()) {

const row = report.next();

const searchTerm = row.searchTermView.searchTerm.trim().toLowerCase();

// Test search term against regex patterns

const isNonBuyer = CONFIG.patterns.some(pattern = pattern.test(searchTerm));

if (isNonBuyer) {

matchedCount++;

if (existingNegatives.has(searchTerm)) {

Logger.log([SKIPPED] Already in negative list: "${searchTerm}");

continue;

}

Logger.log([MATCH] Non-buyer query detected: "${searchTerm}" in Campaign: "${row.campaign.name}");

if (!CONFIG.dryRun) {

// Add as phrase match negative to shared list

negativeList.addNegativeKeyword("${searchTerm}");

existingNegatives.add(searchTerm);

addedCount++;

}

}

}

Logger.log(Finished processing. Total matched: ${matchedCount}. Total newly excluded: ${addedCount}.);

}

function getOrCreateNegativeList(listName) {

const iterator = AdsApp.negativeKeywordLists()

.withCondition(Name = '${listName}')

.get();

if (iterator.hasNext()) {

return iterator.next();

}

if (CONFIG.dryRun) {

Logger.log([DRY RUN] Would create Shared Negative List: "${listName}");

return null;

}

Logger.log(Creating new Shared Negative List: "${listName}");

const builder = AdsApp.newNegativeKeywordListBuilder()

.withName(listName)

.build();

return builder.getResult();

}

function getExistingNegatives(negativeList) {

const set = new Set();

if (!negativeList) return set;

const iterator = negativeList.getNegativeKeywords();

while (iterator.hasNext()) {

const item = iterator.next();

// Clean wrapper quotes or brackets

const text = item.getText().replace(/["\[\]]/g, '').toLowerCase();

set.add(text);

}

return set;

}

---

How to Deploy and Schedule the Script in Google Ads

Deploying scripts in the modern Google Ads interface takes fewer than five minutes:

1. Open Google Ads: Log into your primary account or MCC.

2. Navigate to Scripts: In the top navigation menu, go to Tools and Settings (or the Admin wrench icon) Bulk Actions Scripts.

3. Create a New Script: Click the blue + button to create a new script.

4. Paste the Code: Clear any default placeholder code and paste the complete script provided above.

5. Authorize the Script: Click the Authorize button at the bottom of the editor to grant the script permission to query your Search Terms and edit Shared Negative Lists.

6. Run a Dry Run Preview: Leave CONFIG.dryRun = true; on line 18 and click Preview. Check the logs to ensure it flags expected queries without false positives.

7. Switch to Production: Change CONFIG.dryRun = false;, click Save, and then click Schedule.

8. Set Execution Frequency: Set the frequency to run Daily (ideally in early morning hours, e.g., 3:00 AM) so non-buyer queries from the previous day are excluded before peak business hours.

9. Attach Shared List to Campaigns: Go to Tools & Settings Shared Library Negative Keyword Lists, locate Automated Regex Exclusions, and apply it to all relevant Search campaigns.

Workflow: Automated Regex Negative Processing

[Google Ads Search Terms]

│

▼

[Daily Script Execution (3:00 AM)]

│

▼

[Regex Evaluation Engine] ──(No Match)──► [Ignored / Allowed]

│

(Pattern Match)

│

▼

[Shared Negative List] ──► [Applied to All Search Campaigns]

---

Edge Cases, Regex Pitfalls, and How to Avoid Over-Exclusion

When deploying automated negative keyword scripts, minor syntax errors can inadvertently block high-converting traffic. Here are critical edge cases to anticipate:

1. Missing Word Boundaries (\b)

If you search for the subpattern cat, you will accidentally match catalog, catering, education, and certificate. Always wrap standalone words in \b:

• ❌ Dangerous: /free/i (matches freelance, freeze, carefree)

• ✅ Safe: /\bfree\b/i (matches only the isolated word "free")

2. Dual-Use Industry Terms

Certain words indicate non-buyer intent in consumer industries but represent purchase intent in B2B. For example, job is a non-buyer career term for most companies, but for a commercial printing service or construction subcontractor, "print job quote" or "subcontractor job bidding" is high-intent revenue. Use negative lookarounds or strict compound phrases to protect valid commercial terms.

3. Case Insensitivity in JavaScript

JavaScript regular expressions are case-sensitive by default unless configured with the i flag. A query like "FREE trial" will bypass /\bfree\b/ unless you declare it as /\bfree\b/i or initialize it with new RegExp("\\bfree\\b", "i").

4. Special Character Escaping

Search queries frequently contain characters like +, ?, /, or .. If your regex tests for terms like c++, node.js, or .pdf, ensure you properly escape periods and operators:

• ❌ Broken: /node.js/i (the dot matches any single character, including "nodesjs" or "node-js")

• ✅ Correct: /node\.js/i

For a complete review of manual vs. automated account hygiene, explore our PPC audit checklist.

---

Measuring Script Impact and Account Hygiene

To ensure your regex exclusion automation is performing effectively, track three key account metrics across 30-, 60-, and 90-day intervals:

Core Impact Metrics

├── Wasted Spend Ratio = (Spend on 0-Conversion Queries) / (Total Search Spend)

├── Click-Through Rate = Total Clicks / Total Impressions (Expect +15-25% lift)

└── Cost Per Acquisition = Total Ad Spend / Total Conversions (Expect -10-20% decrease)

1. Wasted Spend Percentage: Calculate total spend allocated to search terms generating zero conversions before and after script implementation. Accounts using aggressive regex filtering typically reduce wasted spend by 18% to 35% within the first month.

2. Search Term CTR Lift: By filtering out informational searches where searchers ignore your commercial ad copy, your overall search ad Click-Through Rate should rise. If you want to benchmark your numbers against industry standards, check our guide on what is a good CTR for Google Ads.

3. CPA Reduction: When your budget stops bleeding into non-converting academic, career, and login queries, Smart Bidding allocates more spend toward transactional auctions, lowering your overall Cost Per Acquisition.

For teams managing complex accounts who want to combine automated query sanitization with real-time budget and bid adjustments, exploring a dedicated PPC management software solution like AdTurbo helps automate negative matching, bid distribution, and campaign structure at scale.

---

Related Guides

• How to Find Negative Keywords in Google Ads (Step by Step)

• Negative Keywords: 100+ Examples and Lists for Google Ads

• Google Ads Optimization Checklist: 15 Things to Check Every Week

---

Frequently Asked Questions

How does negative lookahead work in regex for Google Ads scripts?

A negative lookahead (?!pattern) checks whether a specific sequence follows the current point in a string without including those characters in the match. In Google Ads scripts, negative lookaheads allow you to flag terms that contain non-buyer keywords unless they are paired with high-intent modifiers like "buy" or "enterprise." This prevents your script from over-excluding profitable, multi-word queries.

What is (?: in regular expressions?

The (?: ... ) syntax defines a non-capturing group. It allows you to group multiple alternative words or operators together—such as (?:login|portal|dashboard)—without storing the captured match in memory. In Google Ads JavaScript scripts, using non-capturing groups speeds up execution performance when evaluating thousands of search query rows.

Can I use regex directly inside the Google Ads negative keywords interface?

No, the native Google Ads user interface does not accept regex syntax for negative keywords. It only supports exact match [term], phrase match "term", and broad match term. However, you can write a Google Ads Script that evaluates incoming queries against regex patterns and programmatically uploads matching terms into standard negative keyword lists.

How to do negation in regex when matching non-buyer search terms?

Negation in regular expressions is achieved using character classes with a caret (such as [^a-z]) or lookaround assertions like negative lookahead (?!...) and negative lookbehind (?<!...). For Google Ads negative query scripts, you typically evaluate search terms against an array of unwanted regex patterns using JavaScript's .test() method, excluding any query that returns true.