How to Use Regular Expressions in Google Apps Script

Apps Script runs on JavaScript, so all standard JS regex features work out of the box. Whether you're validating emails, extracting data from strings, or cleaning messy text, regex is a powerful tool to have.

Basic matching

function basicMatch() { const text = 'Contact us at [email protected] or [email protected]'; const pattern = /[\w.-]+@[\w.-]+\.\w+/g; const matches = text.match(pattern); Logger.log(matches); // ['[email protected]', '[email protected]'] }

Test if a string matches a pattern

function validateEmail(email) { const pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return pattern.test(email); } function validatePhone(phone) { const pattern = /^\+?[\d\s\-().]{7,15}$/; return pattern.test(phone); } function validateUrl(url) { const pattern = /^https?:\/\/[^\s/$.?#].[^\s]*$/i; return pattern.test(url); } // Usage: // Logger.log(validateEmail('[email protected]')); // true // Logger.log(validateEmail('not-an-email')); // false

Extract data from strings

function extractNumbers(text) { return text.match(/\d+(\.\d+)?/g) || []; } function extractUrls(text) { return text.match(/https?:\/\/[^\s]+/g) || []; } function extractHashtags(text) { return text.match(/#\w+/g) || []; } // Usage: // extractNumbers('Revenue: $1,234.56, Count: 42') → ['1', '234.56', '42'] // extractUrls('Visit https://example.com today') → ['https://example.com'] // extractHashtags('Loving #AppsScript and #Google') → ['#AppsScript', '#Google']

Capture groups: extract specific parts

function parseDate(text) { const pattern = /(\d{1,2})\/(\d{1,2})\/(\d{4})/; const match = text.match(pattern); if (!match) return null; return { day: match[1], month: match[2], year: match[3] }; } function extractDomain(email) { const match = email.match(/@([\w.-]+)/); return match ? match[1] : null; } // parseDate('Invoice date: 15/03/2025') → { day: '15', month: '03', year: '2025' } // extractDomain('[email protected]') → 'company.com'

Replace text with regex

function cleanText() { const messy = ' Hello, World! Extra spaces. '; // Collapse multiple spaces into one const clean = messy.trim().replace(/\s+/g, ' '); Logger.log(clean); // 'Hello, World! Extra spaces.' } function removeSpecialChars(text) { return text.replace(/[^a-zA-Z0-9\s]/g, ''); } function slugify(text) { return text .toLowerCase() .trim() .replace(/[^\w\s-]/g, '') .replace(/[\s_-]+/g, '-') .replace(/^-+|-+$/g, ''); } // slugify('Hello, World! 2025') → 'hello-world-2025'

Apply regex across a Sheets column

function extractEmailsFromSheet() { const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); const data = sheet.getRange('A2:A100').getValues(); const emailPattern = /[\w.-]+@[\w.-]+\.\w+/; const results = data.map(([cell]) => { if (!cell) return ['']; const match = String(cell).match(emailPattern); return [match ? match[0] : '']; }); sheet.getRange('B2:B100').setValues(results); Logger.log('Emails extracted to column B.'); }

Use regex in Google Docs (replaceText)

body.replaceText() in Docs uses Java regex syntax — slightly different from JavaScript:

function cleanDocText() { const body = DocumentApp.getActiveDocument().getBody(); // Remove double spaces body.replaceText(' +', ' '); // Replace US date format MM/DD/YYYY with YYYY-MM-DD // Java regex uses \\d instead of \d body.replaceText('(\\d{2})/(\\d{2})/(\\d{4})', '$3-$1-$2'); Logger.log('Document text cleaned.'); }

Search Gmail with regex-like queries

GmailApp uses Gmail search syntax, not regex — but you can apply regex post-fetch:

function findEmailsWithPattern() { const threads = GmailApp.search('subject:invoice'); const invoicePattern = /INV-\d{4,6}/i; threads.forEach(thread => { const subject = thread.getFirstMessageSubject(); const match = subject.match(invoicePattern); if (match) { Logger.log('Invoice ID found: ' + match[0]); } }); }

Quick regex reference

PatternMatches
\dAny digit (0–9)
\wWord character (a-z, A-Z, 0-9, _)
\sWhitespace
+One or more
*Zero or more
?Zero or one
^Start of string
$End of string
[abc]Any of a, b, c
(a|b)a or b
(...)Capture group

Tips

  • Use the g flag for global matching (/pattern/g) to find all matches, not just the first.
  • Use the i flag for case-insensitive matching (/pattern/i).
  • string.match(/pattern/g) returns an array of matches or null — always guard with || [].
  • body.replaceText() in Docs uses Java regex, not JS — escape differently and use $1, $2 for back-references.