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.
functioncleanText(){const messy =' Hello, World! Extra spaces. ';// Collapse multiple spaces into oneconst clean = messy.trim().replace(/\s+/g,' ');Logger.log(clean);// 'Hello, World! Extra spaces.'}functionremoveSpecialChars(text){return text.replace(/[^a-zA-Z0-9\s]/g,'');}functionslugify(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
functionextractEmailsFromSheet(){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:
functioncleanDocText(){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:
functionfindEmailsWithPattern(){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
Pattern
Matches
\d
Any digit (0–9)
\w
Word character (a-z, A-Z, 0-9, _)
\s
Whitespace
+
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.