In this post we are going to cover REGEXP_REPLACE, REGEXP_SUBSTR and REGEXP_INSTR in Snowflake.
Episode 68 only asked questions of a string. These three change it or take it apart. REGEXP_REPLACE rewrites the part that matched. REGEXP_SUBSTR hands you the part that matched. REGEXP_INSTR tells you where it was.
We will start with the simplest REGEXP_REPLACE we can write and build it up step by step. On the way we will cover capture groups, which are the reason to reach for these functions at all, and the one behaviour in this post that can leave broken data looking clean.
Every query below was run on a real Snowflake account, and every result you see is the output it gave back.
Episode 69 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.
- Let's create some sample data
- Let's start with REGEXP_REPLACE
- Now let's try the position and occurrence arguments
- What happens if we leave the replacement out?
- Now let's keep part of what we matched
- Two more things about groups
- Now let's reformat the phone numbers
- Now let's pull the match out with REGEXP_SUBSTR
- What do we get when it finds nothing?
- Which occurrence do we want?
- Can we ask for one capture group by number?
- Now let's find out where the match is
- So what does each function say for not found?
- Now let's try the return option
- Let's parse the region column for real
- Let's clean the amount with one expression
- One last thing: all three functions on one row
Let's create some sample data
Everything on this page reads one of two tables. EMPLOYEES gives us a clean, predictable EMAIL column, which is useful for learning what a function does because you can check the answer by eye. SALES_RAW gives us the opposite: text that came out of a spreadsheet and has never been validated.
Copy this into a Snowflake worksheet and run it once.
-- Sample data for this post.
-- Run this once. SALES_RAW is deliberately messy: three date formats, four
-- phone formats, currency symbols, mixed-case region codes and one amount
-- that is not a number.
USE DATABASE DEMO_DB;
USE SCHEMA PUBLIC;
CREATE OR REPLACE TABLE SALES_RAW (
ROW_ID INT,
CUSTOMER_TXT VARCHAR,
AMOUNT_TXT VARCHAR,
DATE_TXT VARCHAR,
REGION_TXT VARCHAR,
PHONE_TXT VARCHAR
);
INSERT INTO SALES_RAW VALUES
(1, ' Northwind Traders ', '$4,200.00', '2023-01-12', 'us-east', '(704) 555-0142'),
(2, 'blue ridge supply', '890.50', '01/28/2023', 'US-EAST', '704-555-0198'),
(3, 'KESTREL ANALYTICS', '$6,150', '14-Feb-2023', 'ca-west', '+1 416 555 0117'),
(4, 'Harbour Foods ', '2,310.75', '2023-03-09', 'CA-West', '604.555.0163'),
(5, 'Alpine Logistics', 'N/A', '2023-04-05', 'eu-central', '+41 44 555 0188'),
(6, ' Delta Print Co', '$640.00', '05/21/2023', 'us-east', '919-555-0124'),
(7, 'Meridian Health', '9,250.00', '14-Aug-2023', 'US-East', '(617) 555-0179'),
(8, 'copper kettle ltd', '$1,080', '2024-09-29', 'uk-north', '+44 161 555 0133');
-- The EMPLOYEES table supplies the EMAIL column we take apart. It is the one
-- from Episode 1, so you already have it if you have been following along.Let's look at the clean table first.
SELECT EMP_ID, FIRST_NAME, LAST_NAME, EMAIL FROM EMPLOYEES ORDER BY EMP_ID;| EMP_ID | FIRST_NAME | LAST_NAME | |
|---|---|---|---|
| 1 | Aisha | Khan | aisha.khan@example.com |
| 2 | Marcus | Reid | marcus.reid@example.com |
| 3 | Lena | Fischer | lena.fischer@example.com |
| 4 | Tomas | Novak | tomas.novak@example.com |
| 5 | Priya | Raman | priya.raman@example.com |
| 6 | Daniel | O'Connor | daniel.oconnor@example.com |
| 7 | Sofia | Marino | sofia.marino@example.com |
| 8 | Grace | Lin | grace.lin@example.com |
Eight employees, and every email follows the same shape. First name, a dot, last name, then @example.com. That shape is what the capture groups later on will pull apart.
And now the messy one.
SELECT ROW_ID, CUSTOMER_TXT, AMOUNT_TXT, DATE_TXT, REGION_TXT, PHONE_TXT
FROM SALES_RAW ORDER BY ROW_ID;| ROW_ID | CUSTOMER_TXT | AMOUNT_TXT | DATE_TXT | REGION_TXT | PHONE_TXT |
|---|---|---|---|---|---|
| 1 | Northwind Traders | $4,200.00 | 2023-01-12 | us-east | (704) 555-0142 |
| 2 | blue ridge supply | 890.50 | 01/28/2023 | US-EAST | 704-555-0198 |
| 3 | KESTREL ANALYTICS | $6,150 | 14-Feb-2023 | ca-west | +1 416 555 0117 |
| 4 | Harbour Foods | 2,310.75 | 2023-03-09 | CA-West | 604.555.0163 |
| 5 | Alpine Logistics | N/A | 2023-04-05 | eu-central | +41 44 555 0188 |
| 6 | Delta Print Co | $640.00 | 05/21/2023 | us-east | 919-555-0124 |
| 7 | Meridian Health | 9,250.00 | 14-Aug-2023 | US-East | (617) 555-0179 |
| 8 | copper kettle ltd | $1,080 | 2024-09-29 | uk-north | +44 161 555 0133 |
Eight rows, and almost every column is inconsistent on purpose. DATE_TXT holds three different date formats. PHONE_TXT holds four different phone formats, three of them with a country code. AMOUNT_TXT has currency symbols, thousands separators and one value that is simply not a number. REGION_TXT is the same handful of codes in whatever case somebody typed.
This is the table Episode 67 cleaned with REPLACE, TRANSLATE and SPLIT_PART. Two of the queries below answer the same questions with regular expressions and then check that both tools agree, which is the only way to be sure a rewrite changed nothing.
Let's start with REGEXP_REPLACE
REGEXP_REPLACE takes the value, the pattern and the replacement, and by default it replaces every match, not the first one.
Let's run the two patterns that do most of the work in practice. A negated class to keep only what we want, and a plain class to mask what we do not. Episode 67's TRANSLATE answer goes in the last column for comparison.
SELECT ROW_ID, PHONE_TXT,
REGEXP_REPLACE(PHONE_TXT, '[^0-9]', '') AS DIGITS_ONLY,
REGEXP_REPLACE(PHONE_TXT, '[0-9]', '#') AS DIGITS_MASKED,
TRANSLATE(PHONE_TXT, '()-. +', '') AS TRANSLATE_FOR_COMPARISON
FROM SALES_RAW
ORDER BY ROW_ID;| ROW_ID | PHONE_TXT | DIGITS_ONLY | DIGITS_MASKED | TRANSLATE_FOR_COMPARISON |
|---|---|---|---|---|
| 1 | (704) 555-0142 | 7045550142 | (###) ###-#### | 7045550142 |
| 2 | 704-555-0198 | 7045550198 | ###-###-#### | 7045550198 |
| 3 | +1 416 555 0117 | 14165550117 | +# ### ### #### | 14165550117 |
| 4 | 604.555.0163 | 6045550163 | ###.###.#### | 6045550163 |
| 5 | +41 44 555 0188 | 41445550188 | +## ## ### #### | 41445550188 |
| 6 | 919-555-0124 | 9195550124 | ###-###-#### | 9195550124 |
| 7 | (617) 555-0179 | 6175550179 | (###) ###-#### | 6175550179 |
| 8 | +44 161 555 0133 | 441615550133 | +## ### ### #### | 441615550133 |
[^0-9] means “anything that is not a digit”, so replacing it with an empty string strips the phone number down to digits.
[0-9] is the same class the other way round, and replacing it with # leaves the punctuation standing. That is a quick way to see the format each row was typed in.
DIGITS_ONLY and TRANSLATE_FOR_COMPARISON look identical. So let's let Snowflake say so rather than trusting our eyes.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT_IF(REGEXP_REPLACE(PHONE_TXT, '[^0-9]', '')
= TRANSLATE(PHONE_TXT, '()-. +', '')) AS AGREE
FROM SALES_RAW;| ROWS_TOTAL | AGREE |
|---|---|
| 8 | 8 |
Eight rows, eight agreements. Same answer, different tool. TRANSLATE is the better choice when you can list the characters. The regular expression is the better choice when you can only describe them.
Now let's try the position and occurrence arguments
After the replacement come two optional arguments: the position to start searching from, and which occurrence to replace.
Let's run the same string five ways and read them against each other.
SELECT REGEXP_REPLACE('a-b-c-d', '-', '+') AS ALL_OF_THEM,
REGEXP_REPLACE('a-b-c-d', '-', '+', 1, 1) AS FIRST_ONLY,
REGEXP_REPLACE('a-b-c-d', '-', '+', 1, 2) AS SECOND_ONLY,
REGEXP_REPLACE('a-b-c-d', '-', '+', 1, 0) AS OCCURRENCE_ZERO,
REGEXP_REPLACE('a-b-c-d', '-', '+', 4) AS FROM_POSITION_4;| ALL_OF_THEM | FIRST_ONLY | SECOND_ONLY | OCCURRENCE_ZERO | FROM_POSITION_4 |
|---|---|---|---|---|
| a+b+c+d | a+b-c-d | a-b+c-d | a+b+c+d | a-b+c+d |
Reading across: ALL_OF_THEM has no occurrence argument and replaces all of them. FIRST_ONLY replaces the first dash. SECOND_ONLY replaces the second. And FROM_POSITION_4 starts searching far enough in to skip the first dash entirely, so the two remaining dashes are replaced.
Look at OCCURRENCE_ZERO. Occurrence 0 does not mean “none”. It means every match, and the grid shows it returning exactly what the no-argument form returned. If you are computing that argument rather than typing it, a zero is not a safe no-op.
What happens if we leave the replacement out?
Let's find out, and put a NULL subject and a pattern that is not there in the same grid.
SELECT REGEXP_REPLACE('a-b-c', '-') AS NO_REPLACEMENT_ARG,
REGEXP_REPLACE('a-b-c', '-', '') AS EMPTY_REPLACEMENT,
REGEXP_REPLACE(NULL, '-', '+') AS SUBJECT_IS_NULL,
REGEXP_REPLACE('a-b-c', 'x', '+') AS PATTERN_NOT_PRESENT;| NO_REPLACEMENT_ARG | EMPTY_REPLACEMENT | SUBJECT_IS_NULL | PATTERN_NOT_PRESENT |
|---|---|---|---|
| abc | abc | NULL | a-b-c |
With two arguments REGEXP_REPLACE deletes, exactly as the two-argument REPLACE did in Episode 67. NO_REPLACEMENT_ARG and EMPTY_REPLACEMENT come back the same.
A NULL subject gives NULL.
And PATTERN_NOT_PRESENT is the one to remember. The pattern x is not in a-b-c, and the function hands the input straight back. Keep that column in mind. It gets a step of its own shortly.
Now let's keep part of what we matched
This is the reason to reach for REGEXP_REPLACE over plain REPLACE. Wrap part of the pattern in parentheses and it becomes a capture group. In the replacement, \\1, \\2 and \\3 give you back what those groups matched.
Which means we can reorder a value in one expression. Let's capture year, month and day out of the date column and write them back the other way round.
The backreference itself is one backslash and a digit. Inside a SQL string literal the backslash is an escape character, so you type two of them. That is why every pattern and replacement on this page is written \\1 rather than \1, and the same goes for an escaped dot: \\. in the literal is \. in the pattern.
SELECT DATE_TXT,
REGEXP_REPLACE(DATE_TXT, '([0-9]{4})-([0-9]{2})-([0-9]{2})',
'\\3/\\2/\\1') AS ISO_TO_UK,
REGEXP_REPLACE(DATE_TXT, '([0-9]{2})/([0-9]{2})/([0-9]{4})',
'\\3-\\1-\\2') AS US_TO_ISO
FROM SALES_RAW
ORDER BY ROW_ID;| DATE_TXT | ISO_TO_UK | US_TO_ISO |
|---|---|---|
| 2023-01-12 | 12/01/2023 | 2023-01-12 |
| 01/28/2023 | 01/28/2023 | 2023-01-28 |
| 14-Feb-2023 | 14-Feb-2023 | 14-Feb-2023 |
| 2023-03-09 | 09/03/2023 | 2023-03-09 |
| 2023-04-05 | 05/04/2023 | 2023-04-05 |
| 05/21/2023 | 05/21/2023 | 2023-05-21 |
| 14-Aug-2023 | 14-Aug-2023 | 14-Aug-2023 |
| 2024-09-29 | 29/09/2024 | 2024-09-29 |
The ISO_TO_UK column captures the three pieces and writes them back as \\3/\\2/\\1. It worked on four rows: ROW_ID 1, 4, 5 and 8, the four written in ISO form.
Now look at ROW_ID 2, 3, 6 and 7 in that same column. Nothing happened to them. Four of the eight rows came back exactly as they went in, because the pattern wants four digits, a dash, two digits, a dash and two digits, and those rows are not written that way.
US_TO_ISO is the mirror image. It matches the mm/dd/yyyy rows, which are ROW_ID 2 and 6, and leaves everything else alone. ROW_ID 3 and 7 are in dd-Mon-yyyy form and match neither pattern, so they pass through both columns untouched.
Two more things about groups
Before we leave groups, let's run four of them on one small string and look at the edges.
SELECT REGEXP_REPLACE('abc', '(a)(b)(c)', '[\\1][\\2][\\3]') AS ALL_THREE,
REGEXP_REPLACE('abc', '(a)(x)?(c)?', '[\\1][\\2]') AS MIDDLE_OPTIONAL,
REGEXP_REPLACE('abc', '(a)', '\\1\\1\\1') AS REPEATED_GROUP,
REGEXP_REPLACE('abc', 'b', '[\\0]') AS BACKSLASH_ZERO;| ALL_THREE | MIDDLE_OPTIONAL | REPEATED_GROUP | BACKSLASH_ZERO |
|---|---|---|---|
| [a][b][c] | [a][]bc | aaabc | a[b]c |
ALL_THREEis the ordinary case: three groups, three backreferences, each one bracketed in the output.MIDDLE_OPTIONALis the one to watch. The second group is optional and did not match, and\\2came out as an empty string, not asNULL. So an unmatched group quietly contributes nothing instead of making the whole expressionNULL.REPEATED_GROUPshows that a backreference can be used as many times as you like.BACKSLASH_ZEROis\\0, which is the whole match rather than any group. Useful for wrapping something you matched without having to capture it.
Now let's reformat the phone numbers
Here is the same idea on a job that looks like real work. Strip each phone number to digits, then reformat it as (nnn) nnn-nnnn. Three groups of digits, anchored at both ends so only a ten-digit number can match.
SELECT PHONE_TXT,
REGEXP_REPLACE(REGEXP_REPLACE(PHONE_TXT, '[^0-9]', ''),
'^([0-9]{3})([0-9]{3})([0-9]{4})$',
'(\\1) \\2-\\3') AS US_FORMAT
FROM SALES_RAW
ORDER BY ROW_ID;| PHONE_TXT | US_FORMAT |
|---|---|
| (704) 555-0142 | (704) 555-0142 |
| 704-555-0198 | (704) 555-0198 |
| +1 416 555 0117 | 14165550117 |
| 604.555.0163 | (604) 555-0163 |
| +41 44 555 0188 | 41445550188 |
| 919-555-0124 | (919) 555-0124 |
| (617) 555-0179 | (617) 555-0179 |
| +44 161 555 0133 | 441615550133 |
Five rows came out formatted: ROW_ID 1, 2, 4, 6 and 7. Three did not. ROW_ID 3, 5 and 8 are sitting there as bare digit strings.
The reason is in the digits themselves. Those three numbers carry a country code, so after stripping they are eleven, eleven and twelve digits long, and the anchored pattern wants exactly ten.
When the pattern does not match, REGEXP_REPLACE returns your input unchanged. Not NULL. Not an error. Not a warning. Your original string, handed straight back.
That is the correct and documented behaviour, and it is also why a reformatting job can pass rows through raw and leave no trace. The three unformatted rows above do not look broken. They look like data that was already fine. Nothing downstream can tell the difference.
The defence is to stop asking the function whether it worked and ask the data instead. Any of these turns a silent pass into something you can see.
- Count the rows that still fail the output shape, with
COUNT_IFand aREGEXP_LIKEon the result, as in Episode 68. - Compare the result to the input. If they are equal, the pattern missed.
- Put the expected length or format in a
CASEand label the misses, so they arrive in the report as misses rather than as values.
This is not a reason to avoid REGEXP_REPLACE. It is a reason never to ship one without a check beside it.
Now let's pull the match out with REGEXP_SUBSTR
REGEXP_SUBSTR is the same idea as REGEXP_REPLACE with the answer turned round. Instead of replacing the match, it hands us the match.
Let's point three different patterns at the one email column.
SELECT EMAIL,
REGEXP_SUBSTR(EMAIL, '[a-z]+') AS FIRST_RUN_OF_LETTERS,
REGEXP_SUBSTR(EMAIL, '@[a-z.]+') AS FROM_THE_AT_SIGN,
REGEXP_SUBSTR(EMAIL, '[a-z]+\\.[a-z]+') AS DOTTED_PAIR
FROM EMPLOYEES
ORDER BY EMP_ID;| FIRST_RUN_OF_LETTERS | FROM_THE_AT_SIGN | DOTTED_PAIR | |
|---|---|---|---|
| aisha.khan@example.com | aisha | @example.com | aisha.khan |
| marcus.reid@example.com | marcus | @example.com | marcus.reid |
| lena.fischer@example.com | lena | @example.com | lena.fischer |
| tomas.novak@example.com | tomas | @example.com | tomas.novak |
| priya.raman@example.com | priya | @example.com | priya.raman |
| daniel.oconnor@example.com | daniel | @example.com | daniel.oconnor |
| sofia.marino@example.com | sofia | @example.com | sofia.marino |
| grace.lin@example.com | grace | @example.com | grace.lin |
[a-z]+ finds the first run of letters, which is the first name. @[a-z.]+ finds the at sign and everything after it, which is the domain. [a-z]+\\.[a-z]+ finds a dotted pair, which is the local part of the address.
One column of input, three different pieces of it out.
What do we get when it finds nothing?
Let's ask for a pattern that is not in the string, and ask two follow-up questions about the answer in the same grid.
SELECT REGEXP_SUBSTR('abc', 'z') AS NO_MATCH,
REGEXP_SUBSTR('abc', 'z') IS NULL AS IS_IT_NULL,
REGEXP_SUBSTR('abc', 'z') = '' AS IS_IT_EMPTY_STRING,
REGEXP_SUBSTR(NULL, 'a') AS SUBJECT_IS_NULL,
REGEXP_COUNT('abc', 'z') AS COUNT_SAYS;| NO_MATCH | IS_IT_NULL | IS_IT_EMPTY_STRING | SUBJECT_IS_NULL | COUNT_SAYS |
|---|---|---|---|---|
| NULL | TRUE | NULL | NULL | 0 |
NO_MATCH is NULL, not an empty string. IS_IT_NULL confirms it with IS NULL, which comes back TRUE.
IS_IT_EMPTY_STRING is the one worth sitting with. It asks whether the result equals the empty string, and the answer is neither TRUE nor FALSE. It is NULL, because comparing anything to NULL gives NULL. A WHERE clause written that way filters out every row and reports no error.
SUBJECT_IS_NULL is the easy case. A NULL in gives a NULL out.
And COUNT_SAYS is REGEXP_COUNT from Episode 68, on the same absent pattern, for contrast. It answers 0. Same question, same family, different kind of answer.
Which occurrence do we want?
REGEXP_SUBSTR takes an occurrence argument too. Let's ask the same pattern for its first, second and third match, and then for one that cannot exist.
SELECT EMAIL,
REGEXP_SUBSTR(EMAIL, '[a-z]+', 1, 1) AS OCCURRENCE_1,
REGEXP_SUBSTR(EMAIL, '[a-z]+', 1, 2) AS OCCURRENCE_2,
REGEXP_SUBSTR(EMAIL, '[a-z]+', 1, 3) AS OCCURRENCE_3,
REGEXP_SUBSTR(EMAIL, '[a-z]+', 1, 9) AS OCCURRENCE_9_PAST_THE_END
FROM EMPLOYEES
ORDER BY EMP_ID;| OCCURRENCE_1 | OCCURRENCE_2 | OCCURRENCE_3 | OCCURRENCE_9_PAST_THE_END | |
|---|---|---|---|---|
| aisha.khan@example.com | aisha | khan | example | NULL |
| marcus.reid@example.com | marcus | reid | example | NULL |
| lena.fischer@example.com | lena | fischer | example | NULL |
| tomas.novak@example.com | tomas | novak | example | NULL |
| priya.raman@example.com | priya | raman | example | NULL |
| daniel.oconnor@example.com | daniel | oconnor | example | NULL |
| sofia.marino@example.com | sofia | marino | example | NULL |
| grace.lin@example.com | grace | lin | example | NULL |
The same [a-z]+ pattern picks out the first name, the last name and the domain name in turn.
OCCURRENCE_9_PAST_THE_END asks for an occurrence that does not exist and gets NULL. That is the same answer as a pattern that never matched at all, which is worth knowing before you try to tell the two cases apart.
Can we ask for one capture group by number?
Yes. REGEXP_SUBSTR can give us a single group instead of the whole match. The group number is the sixth positional argument, which means we have to pass something in the fifth slot, the parameters string, to reach it.
The documentation leads with the e parameter here, which reads like a requirement. It is not, and this is a correction the video makes on itself. Let's run it both ways.
SELECT EMAIL,
REGEXP_SUBSTR(EMAIL, '([a-z]+)\\.([a-z]+)@', 1, 1, 'e', 1) AS GROUP_1_WITH_E,
REGEXP_SUBSTR(EMAIL, '([a-z]+)\\.([a-z]+)@', 1, 1, 'e', 2) AS GROUP_2_WITH_E,
REGEXP_SUBSTR(EMAIL, '([a-z]+)\\.([a-z]+)@', 1, 1, 'c', 1) AS GROUP_1_WITH_C,
REGEXP_SUBSTR(EMAIL, '([a-z]+)\\.([a-z]+)@', 1, 1) AS NO_PARAMS_AT_ALL
FROM EMPLOYEES
ORDER BY EMP_ID;| GROUP_1_WITH_E | GROUP_2_WITH_E | GROUP_1_WITH_C | NO_PARAMS_AT_ALL | |
|---|---|---|---|---|
| aisha.khan@example.com | aisha | khan | aisha | aisha.khan@ |
| marcus.reid@example.com | marcus | reid | marcus | marcus.reid@ |
| lena.fischer@example.com | lena | fischer | lena | lena.fischer@ |
| tomas.novak@example.com | tomas | novak | tomas | tomas.novak@ |
| priya.raman@example.com | priya | raman | priya | priya.raman@ |
| daniel.oconnor@example.com | daniel | oconnor | daniel | daniel.oconnor@ |
| sofia.marino@example.com | sofia | marino | sofia | sofia.marino@ |
| grace.lin@example.com | grace | lin | grace | grace.lin@ |
GROUP_1_WITH_E and GROUP_1_WITH_C are identical column for column. The c flag, which only means case-sensitive matching, honours the group number just as well. What actually matters is that you pass some parameters string at all, so that the sixth argument exists.
NO_PARAMS_AT_ALL proves the negative. With no parameters argument there is no sixth slot, so we get the whole match: first name, dot, last name and the at sign. That is a plausible-looking wrong answer, not an error.
The groups look right. EMPLOYEES happens to hold the first and last names in their own columns, so let's check rather than take it on trust.
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT_IF(UPPER(REGEXP_SUBSTR(EMAIL, '([a-z]+)\\.([a-z]+)@', 1, 1, 'e', 1))
= UPPER(FIRST_NAME)) AS FIRST_NAME_MATCHES,
COUNT_IF(UPPER(REGEXP_SUBSTR(EMAIL, '([a-z]+)\\.([a-z]+)@', 1, 1, 'e', 2))
= UPPER(REPLACE(LAST_NAME, '''', ''))) AS LAST_NAME_MATCHES
FROM EMPLOYEES;| ROWS_TOTAL | FIRST_NAME_MATCHES | LAST_NAME_MATCHES |
|---|---|---|
| 8 | 8 | 8 |
Eight rows, eight first names matched and eight last names matched. Note what the check had to do to get there. It upper-cases both sides, and it strips an apostrophe out of LAST_NAME, because one employee's surname contains one and the pattern's [a-z]+ does not. That is the honest version. The groups agree with the columns once you account for a character the pattern was never asked to match.
Now let's find out where the match is
The third function answers the position question. REGEXP_INSTR is POSITION with a pattern instead of a literal.
Let's look for the at sign, put plain POSITION beside it, and then look for something that is not there.
SELECT EMAIL,
REGEXP_INSTR(EMAIL, '@') AS AT_SIGN_AT,
POSITION('@', EMAIL) AS POSITION_FOR_COMPARISON,
REGEXP_INSTR(EMAIL, '[0-9]') AS FIRST_DIGIT_NOT_PRESENT
FROM EMPLOYEES
ORDER BY EMP_ID;| AT_SIGN_AT | POSITION_FOR_COMPARISON | FIRST_DIGIT_NOT_PRESENT | |
|---|---|---|---|
| aisha.khan@example.com | 11 | 11 | 0 |
| marcus.reid@example.com | 12 | 12 | 0 |
| lena.fischer@example.com | 13 | 13 | 0 |
| tomas.novak@example.com | 12 | 12 | 0 |
| priya.raman@example.com | 12 | 12 | 0 |
| daniel.oconnor@example.com | 15 | 15 | 0 |
| sofia.marino@example.com | 13 | 13 | 0 |
| grace.lin@example.com | 10 | 10 | 0 |
AT_SIGN_AT and POSITION_FOR_COMPARISON agree on every row, which is the point. For a literal you do not need a regular expression, and POSITION says the same thing more cheaply to read.
FIRST_DIGIT_NOT_PRESENT looks for a digit in an email address, finds none, and answers 0.
So what does each function say for not found?
That zero is worth pinning down, because the function next to it answers differently. Let's put the same absent pattern through both.
SELECT REGEXP_INSTR('abc', 'z') AS INSTR_SAYS,
REGEXP_SUBSTR('abc', 'z') AS SUBSTR_SAYS,
REGEXP_INSTR('abc', 'z') IS NULL AS INSTR_IS_NULL,
REGEXP_SUBSTR('abc', 'z') IS NULL AS SUBSTR_IS_NULL;| INSTR_SAYS | SUBSTR_SAYS | INSTR_IS_NULL | SUBSTR_IS_NULL |
|---|---|---|---|
| 0 | NULL | FALSE | TRUE |
Same string, same pattern, same family of functions, and two different answers. REGEXP_INSTR returns 0, which is not NULL. REGEXP_SUBSTR returns NULL, which is not 0.
Here is everything on this page that behaves this way, in one table.
| Function | Pattern not found | Shown in |
|---|---|---|
REGEXP_REPLACE | the input, unchanged | What happens if we leave the replacement out? |
REGEXP_SUBSTR | NULL | What do we get when it finds nothing? |
REGEXP_INSTR | 0 | the grid directly above |
REGEXP_COUNT | 0 | What do we get when it finds nothing? |
There is no way to reason your way to that table. It has to be looked up or tested. Which function you are holding decides whether an absent match shows up as a NULL, as a zero, or as nothing at all.
Now let's try the return option
REGEXP_INSTR takes a fifth argument that says which end of the match we want. Let's run both options on the same match.
SELECT REGEXP_INSTR('abcdef', 'cd') AS DEFAULT_OPTION,
REGEXP_INSTR('abcdef', 'cd', 1, 1, 0) AS OPTION_0_START,
REGEXP_INSTR('abcdef', 'cd', 1, 1, 1) AS OPTION_1_AFTER,
REGEXP_INSTR('abcabc', 'bc', 1, 2) AS SECOND_OCCURRENCE;| DEFAULT_OPTION | OPTION_0_START | OPTION_1_AFTER | SECOND_OCCURRENCE |
|---|---|---|---|
| 3 | 3 | 5 | 5 |
Option 0 is the default and gives the position where the match starts. Option 1 gives the position of the character after it ends. The grid shows both, on the same match, so the difference is visible rather than described.
SECOND_OCCURRENCE asks for the second occurrence instead of the first, on a string that has two.
Option 1 is what you want when you are about to slice the rest of the string. It is already the right starting point for a SUBSTR, with no + 1 for you to get wrong.
Let's parse the region column for real
Put the three functions together and we can take a column apart in one pass. REGION_TXT is a country code, a dash and an area, in whatever case somebody typed.
Let's write one anchored pattern per piece, each asking for its capture group.
SELECT ROW_ID, REGION_TXT,
UPPER(REGEXP_SUBSTR(REGION_TXT, '^([a-zA-Z]+)-', 1, 1, 'e', 1)) AS COUNTRY,
UPPER(REGEXP_SUBSTR(REGION_TXT, '-([a-zA-Z]+)$', 1, 1, 'e', 1)) AS AREA
FROM SALES_RAW
ORDER BY ROW_ID;| ROW_ID | REGION_TXT | COUNTRY | AREA |
|---|---|---|---|
| 1 | us-east | US | EAST |
| 2 | US-EAST | US | EAST |
| 3 | ca-west | CA | WEST |
| 4 | CA-West | CA | WEST |
| 5 | eu-central | EU | CENTRAL |
| 6 | us-east | US | EAST |
| 7 | US-East | US | EAST |
| 8 | uk-north | UK | NORTH |
Two columns out of one, normalised to upper case, with the mixed-case input visible beside them. ^([a-zA-Z]+)- anchors at the start and -([a-zA-Z]+)$ at the end, so neither pattern can wander into the other's half.
Now the check this page has been arguing for. Did it find something on every row?
SELECT COUNT(*) AS ROWS_TOTAL,
COUNT(REGEXP_SUBSTR(REGION_TXT, '^([a-zA-Z]+)-', 1, 1, 'e', 1)) AS COUNTRY_FOUND,
COUNT(REGEXP_SUBSTR(REGION_TXT, '-([a-zA-Z]+)$', 1, 1, 'e', 1)) AS AREA_FOUND
FROM SALES_RAW;| ROWS_TOTAL | COUNTRY_FOUND | AREA_FOUND |
|---|---|---|
| 8 | 8 | 8 |
Eight rows, eight countries found, eight areas found. COUNT over an expression counts non-NULL values, so a row the pattern missed would show up as a smaller number here.
Episode 67 answered the same question with SPLIT_PART. Two completely different tools should produce the same rows, and MINUS is the cheapest way to insist on it.
SELECT ROW_ID, UPPER(REGEXP_SUBSTR(REGION_TXT, '^([a-zA-Z]+)-', 1, 1, 'e', 1)) AS C
FROM SALES_RAW
MINUS
SELECT ROW_ID, UPPER(SPLIT_PART(REGION_TXT, '-', 1)) FROM SALES_RAW;| ROW_ID | C |
|---|
No rows. Every country code the regular expression produced is a country code SPLIT_PART produced too. Read the query before you read more into it than that. It compares the country column and nothing else, so the area column is untested here and would need its own MINUS.
An empty grid is a boring result and a very good one, as long as you know which column it is about.
Let's clean the amount with one expression
The amount column needed two chained REPLACE calls in Episode 67, one for the currency symbol and one for the thousands separator. A negated character class does both at once, because it describes what to keep rather than what to remove.
SELECT ROW_ID, AMOUNT_TXT,
REGEXP_REPLACE(AMOUNT_TXT, '[^0-9.]', '') AS KEEP_DIGITS_AND_DOT,
TRY_TO_NUMBER(REGEXP_REPLACE(AMOUNT_TXT, '[^0-9.]', ''), 12, 2) AS AS_NUMBER
FROM SALES_RAW
ORDER BY ROW_ID;| ROW_ID | AMOUNT_TXT | KEEP_DIGITS_AND_DOT | AS_NUMBER |
|---|---|---|---|
| 1 | $4,200.00 | 4200.00 | 4200.00 |
| 2 | 890.50 | 890.50 | 890.50 |
| 3 | $6,150 | 6150 | 6150.00 |
| 4 | 2,310.75 | 2310.75 | 2310.75 |
| 5 | N/A | NULL | |
| 6 | $640.00 | 640.00 | 640.00 |
| 7 | 9,250.00 | 9250.00 | 9250.00 |
| 8 | $1,080 | 1080 | 1080.00 |
[^0-9.] keeps digits and the decimal point and deletes everything else, which handles the dollar signs and the commas in one expression. TRY_TO_NUMBER then converts without risking an error.
ROW_ID 5 is the interesting one. Let's look at it on its own.
SELECT AMOUNT_TXT,
REGEXP_REPLACE(AMOUNT_TXT, '[^0-9.]', '') AS CLEANED,
LENGTH(REGEXP_REPLACE(AMOUNT_TXT, '[^0-9.]', '')) AS CLEANED_LEN,
TRY_TO_NUMBER(REGEXP_REPLACE(AMOUNT_TXT, '[^0-9.]', ''), 12, 2) AS AS_NUMBER
FROM SALES_RAW
WHERE AMOUNT_TXT = 'N/A';| AMOUNT_TXT | CLEANED | CLEANED_LEN | AS_NUMBER |
|---|---|---|---|
| N/A | 0 | NULL |
N/A contains no digits and no decimal point, so the cleaned value is an empty string. CLEANED_LEN confirms it rather than leaving you to squint at a blank cell, and TRY_TO_NUMBER then returns NULL.
Episode 67 produced a NULL for this same row, but for a different reason. There, the text reaching TRY_TO_NUMBER was text that is not a number. Here the cleaning step removed everything first, so what reaches the conversion is nothing at all. Same NULL, two different causes, and only one of them would survive a stricter cleaning rule.
One last thing: all three functions on one row
To finish, let's put the whole post on a single email address. Both capture groups pulled out, the position of the at sign, the local part isolated by replacing the domain with nothing, and the two halves of the name swapped round.
SELECT EMAIL,
REGEXP_SUBSTR(EMAIL, '([a-z]+)\\.([a-z]+)@', 1, 1, 'e', 1) AS FIRST_FROM_EMAIL,
REGEXP_SUBSTR(EMAIL, '([a-z]+)\\.([a-z]+)@', 1, 1, 'e', 2) AS LAST_FROM_EMAIL,
REGEXP_INSTR(EMAIL, '@') AS AT_SIGN_AT,
REGEXP_REPLACE(EMAIL, '@.*$', '') AS LOCAL_PART,
REGEXP_REPLACE(EMAIL, '^([a-z]+)\\.([a-z]+)@(.*)$', '\\2.\\1@\\3') AS SWAPPED
FROM EMPLOYEES
WHERE EMP_ID = 1;| FIRST_FROM_EMAIL | LAST_FROM_EMAIL | AT_SIGN_AT | LOCAL_PART | SWAPPED | |
|---|---|---|---|---|---|
| aisha.khan@example.com | aisha | khan | 11 | aisha.khan | khan.aisha@example.com |
SWAPPED is the one that would be painful without capture groups. ^([a-z]+)\\.([a-z]+)@(.*)$ captures first name, last name and domain, and the replacement \\2.\\1@\\3 writes them back in a different order. One expression, no string arithmetic, no positions to get wrong.
And it is worth saying one last time. That expression is anchored at both ends, so it works on these addresses and returns the input unchanged on anything shaped differently. The check belongs next to it.
Key points
REGEXP_REPLACEreplaces every match by default. The optional arguments are position then occurrence, and occurrence0means every match, not none.- Leave the replacement out and
REGEXP_REPLACEdeletes, exactly like the two-argumentREPLACE. - Capture groups are the reason to prefer it to
REPLACE.\\1,\\2and\\3in the replacement give back what you matched, so a value can be reordered in one expression.\\0is the whole match, and a group that did not match becomes an empty string rather thanNULL. - When the pattern misses,
REGEXP_REPLACEreturns your input unchanged. No error, noNULL, no warning. Three of the eight phone numbers here went through a reformatting expression raw and came out looking like data that was already clean. REGEXP_SUBSTRreturnsNULLwhen it finds nothing, and comparing thatNULLto''givesNULLrather thanFALSE. AWHEREclause written that way silently matches nothing.REGEXP_INSTRreturns0for the same absent pattern, andREGEXP_COUNTreturns0too. One family, three different answers for “not found”.- The group number is
REGEXP_SUBSTR's sixth positional argument, so you must pass a parameters string to reach it. But it does not have to bee. Thecflag honours the group number too, and with no parameters at all you silently get the whole match instead. REGEXP_INSTR's return option1gives the position just past the match, which is already the right starting point for aSUBSTR.- Regular expressions and the plain string functions should agree.
MINUSagainst theSPLIT_PARTversion returned no rows for the country code, which is how you prove a rewrite changed nothing. OneMINUSproves one column.
In the next post we will move on to numbers. ROUND, CEIL, FLOOR, TRUNC, ABS, SIGN and MOD, including which way a half goes, and why ROUND sides with CEIL on a positive and with FLOOR on a negative.
Every query and every result grid on this page was captured from a live Snowflake account (version 10.34.101) running the demo script for this episode. The EMPLOYEES and SALES_RAW data is invented demo data created by the setup script above. No performance or benchmark claims are made anywhere in this series. Function behaviour follows the Snowflake regular expression function documentation.



No comments:
Post a Comment
Note: Only a member of this blog may post a comment.