Regular expressions (RegExp) for beginners
A regular expression describes the text you want to find. Look for order IDs in a note and see how one symbol changes which characters match.
Find order IDs in a note
ID-- Find these three characters
ID-- Find these three characters
[0-9]- One digit from 0 to 9
ID-- Find these three characters
[0-9]- One digit from 0 to 9
+- One or more consecutive digits
^- Start of the input
ID-- Find these three characters
[0-9]- One digit from 0 to 9
+- One or more consecutive digits
$- End of the input
Matching text
Matching lines: 2 of 3ID-42Match ID-42Note ID-7Match ID-7ID-XNo match
Edit the sample text
Each line is matched separately using JavaScript in your browser.
Symbol reference
| Symbol | Meaning | Pattern and match |
|---|---|---|
[A-Z] | One character from the set or range | [A-Z]7B |
[^0-9] | A leading ^ inside brackets excludes those characters | [^0-9]4A2 |
\d | One ASCII digit, equivalent to [0-9] | \d4 / 4 |
. | Any one character except a line break | A.BA7B |
\ | Escape a special character. \. finds a literal dot | \.pdffile.pdf |
+ | One or more of the preceding item | [0-9]+ID-42 |
* | Zero or more of the preceding item | AB*CAC / ABBC |
? | The preceding item is optional | colou?rcolor / colour |
{n} / {m,n} | Exactly n, or between m and n repetitions | [0-9]{2,3}A7 B42 C123 |
( ) / | | Group items with parentheses. The vertical bar separates alternatives | (AB|CD)-CD-7 |
^ / $ | Start and end of the input. Together they test the whole line in this example | ^ID-[0-9]+$ID-42 |
Test, extract and replace in SQL
With the same note and pattern, the function determines what you get back. Expected results appear below the SQL.
Test for an order ID
Snowflake REGEXP_LIKE checks the whole input, so the text before the ID makes the result FALSE. BigQuery REGEXP_CONTAINS finds the ID anywhere in the input and returns TRUE.
Snowflake
SELECT REGEXP_LIKE(
'Note ID-7', 'ID-[0-9]+'
);Expected result FALSE
BigQuery
SELECT REGEXP_CONTAINS(
'Note ID-7', r'ID-[0-9]+'
);Expected result TRUE
- Substring test in Snowflake
REGEXP_SUBSTR('Note ID-7', 'ID-[0-9]+') IS NOT NULL- Whole-input test in BigQuery
REGEXP_CONTAINS('Note ID-7', r'^ID-[0-9]+$')
Extract just the digits
Match the ID including its prefix. The parentheses capture just the digits, so the result is the string 7.
Snowflake
SELECT REGEXP_SUBSTR(
'Note ID-7', 'ID-([0-9]+)',
1, 1, 'e', 1
);Expected result '7'
BigQuery
SELECT REGEXP_EXTRACT(
'Note ID-7', r'ID-([0-9]+)'
);Expected result '7'
Replace the order ID
Replace the matching ID with ID-*** and keep the surrounding text.
Snowflake
SELECT REGEXP_REPLACE(
'Note ID-7', 'ID-[0-9]+', 'ID-***'
);Expected result 'Note ID-***'
BigQuery
SELECT REGEXP_REPLACE(
'Note ID-7', r'ID-[0-9]+', 'ID-***'
);Expected result 'Note ID-***'