Snowflake SQL Tutorial 69 - REGEXP_REPLACE, REGEXP_SUBSTR, REGEXP_INSTR - Regex 2

Snowflake SQL · Episode 69

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

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
-- 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.

Query
SELECT EMP_ID, FIRST_NAME, LAST_NAME, EMAIL FROM EMPLOYEES ORDER BY EMP_ID;
Result8 rows · 4 columns
EMP_IDFIRST_NAMELAST_NAMEEMAIL
1AishaKhanaisha.khan@example.com
2MarcusReidmarcus.reid@example.com
3LenaFischerlena.fischer@example.com
4TomasNovaktomas.novak@example.com
5PriyaRamanpriya.raman@example.com
6DanielO'Connordaniel.oconnor@example.com
7SofiaMarinosofia.marino@example.com
8GraceLingrace.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.

Query
SELECT ROW_ID, CUSTOMER_TXT, AMOUNT_TXT, DATE_TXT, REGION_TXT, PHONE_TXT
FROM SALES_RAW ORDER BY ROW_ID;
Result8 rows · 6 columns · scroll →
ROW_IDCUSTOMER_TXTAMOUNT_TXTDATE_TXTREGION_TXTPHONE_TXT
1 Northwind Traders $4,200.002023-01-12us-east(704) 555-0142
2blue ridge supply890.5001/28/2023US-EAST704-555-0198
3KESTREL ANALYTICS$6,15014-Feb-2023ca-west+1 416 555 0117
4Harbour Foods 2,310.752023-03-09CA-West604.555.0163
5Alpine LogisticsN/A2023-04-05eu-central+41 44 555 0188
6 Delta Print Co$640.0005/21/2023us-east919-555-0124
7Meridian Health9,250.0014-Aug-2023US-East(617) 555-0179
8copper kettle ltd$1,0802024-09-29uk-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.

The same messy table as last time

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.

Query
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;
Result8 rows · 5 columns
ROW_IDPHONE_TXTDIGITS_ONLYDIGITS_MASKEDTRANSLATE_FOR_COMPARISON
1(704) 555-01427045550142(###) ###-####7045550142
2704-555-01987045550198###-###-####7045550198
3+1 416 555 011714165550117+# ### ### ####14165550117
4604.555.01636045550163###.###.####6045550163
5+41 44 555 018841445550188+## ## ### ####41445550188
6919-555-01249195550124###-###-####9195550124
7(617) 555-01796175550179(###) ###-####6175550179
8+44 161 555 0133441615550133+## ### ### ####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.

Query — do the two tools agree?
SELECT COUNT(*) AS ROWS_TOTAL,
       COUNT_IF(REGEXP_REPLACE(PHONE_TXT, '[^0-9]', '')
                = TRANSLATE(PHONE_TXT, '()-. +', '')) AS AGREE
FROM SALES_RAW;
Result1 row · 2 columns
ROWS_TOTALAGREE
88

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.

Query
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;
Result1 row · 5 columns
ALL_OF_THEMFIRST_ONLYSECOND_ONLYOCCURRENCE_ZEROFROM_POSITION_4
a+b+c+da+b-c-da-b+c-da+b+c+da-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.

Occurrence 0 is not what it looks like

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.

Query
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;
Result1 row · 4 columns
NO_REPLACEMENT_ARGEMPTY_REPLACEMENTSUBJECT_IS_NULLPATTERN_NOT_PRESENT
abcabcNULLa-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.

Why the backslashes are doubled

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.

Query — reordering a date
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;
Result8 rows · 3 columns
DATE_TXTISO_TO_UKUS_TO_ISO
2023-01-1212/01/20232023-01-12
01/28/202301/28/20232023-01-28
14-Feb-202314-Feb-202314-Feb-2023
2023-03-0909/03/20232023-03-09
2023-04-0505/04/20232023-04-05
05/21/202305/21/20232023-05-21
14-Aug-202314-Aug-202314-Aug-2023
2024-09-2929/09/20242024-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.

Query
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;
Result1 row · 4 columns
ALL_THREEMIDDLE_OPTIONALREPEATED_GROUPBACKSLASH_ZERO
[a][b][c][a][]bcaaabca[b]c
  • ALL_THREE is the ordinary case: three groups, three backreferences, each one bracketed in the output.
  • MIDDLE_OPTIONAL is the one to watch. The second group is optional and did not match, and \\2 came out as an empty string, not as NULL. So an unmatched group quietly contributes nothing instead of making the whole expression NULL.
  • REPEATED_GROUP shows that a backreference can be used as many times as you like.
  • BACKSLASH_ZERO is \\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.

Query
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;
Result8 rows · 2 columns
PHONE_TXTUS_FORMAT
(704) 555-0142(704) 555-0142
704-555-0198(704) 555-0198
+1 416 555 011714165550117
604.555.0163(604) 555-0163
+41 44 555 018841445550188
919-555-0124(919) 555-0124
(617) 555-0179(617) 555-0179
+44 161 555 0133441615550133

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.

The quiet failure

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_IF and a REGEXP_LIKE on 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 CASE and 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.

Query
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;
Result8 rows · 4 columns
EMAILFIRST_RUN_OF_LETTERSFROM_THE_AT_SIGNDOTTED_PAIR
aisha.khan@example.comaisha@example.comaisha.khan
marcus.reid@example.commarcus@example.commarcus.reid
lena.fischer@example.comlena@example.comlena.fischer
tomas.novak@example.comtomas@example.comtomas.novak
priya.raman@example.compriya@example.compriya.raman
daniel.oconnor@example.comdaniel@example.comdaniel.oconnor
sofia.marino@example.comsofia@example.comsofia.marino
grace.lin@example.comgrace@example.comgrace.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.

Query
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;
Result1 row · 5 columns
NO_MATCHIS_IT_NULLIS_IT_EMPTY_STRINGSUBJECT_IS_NULLCOUNT_SAYS
NULLTRUENULLNULL0

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.

Query
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;
Result8 rows · 5 columns
EMAILOCCURRENCE_1OCCURRENCE_2OCCURRENCE_3OCCURRENCE_9_PAST_THE_END
aisha.khan@example.comaishakhanexampleNULL
marcus.reid@example.commarcusreidexampleNULL
lena.fischer@example.comlenafischerexampleNULL
tomas.novak@example.comtomasnovakexampleNULL
priya.raman@example.compriyaramanexampleNULL
daniel.oconnor@example.comdanieloconnorexampleNULL
sofia.marino@example.comsofiamarinoexampleNULL
grace.lin@example.comgracelinexampleNULL

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.

Query — 'e' and 'c', same group number
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;
Result8 rows · 5 columns
EMAILGROUP_1_WITH_EGROUP_2_WITH_EGROUP_1_WITH_CNO_PARAMS_AT_ALL
aisha.khan@example.comaishakhanaishaaisha.khan@
marcus.reid@example.commarcusreidmarcusmarcus.reid@
lena.fischer@example.comlenafischerlenalena.fischer@
tomas.novak@example.comtomasnovaktomastomas.novak@
priya.raman@example.compriyaramanpriyapriya.raman@
daniel.oconnor@example.comdanieloconnordanieldaniel.oconnor@
sofia.marino@example.comsofiamarinosofiasofia.marino@
grace.lin@example.comgracelingracegrace.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.

Query — the check
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;
Result1 row · 3 columns
ROWS_TOTALFIRST_NAME_MATCHESLAST_NAME_MATCHES
888

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.

Query
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;
Result8 rows · 4 columns
EMAILAT_SIGN_ATPOSITION_FOR_COMPARISONFIRST_DIGIT_NOT_PRESENT
aisha.khan@example.com11110
marcus.reid@example.com12120
lena.fischer@example.com13130
tomas.novak@example.com12120
priya.raman@example.com12120
daniel.oconnor@example.com15150
sofia.marino@example.com13130
grace.lin@example.com10100

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.

Query — the same absent pattern, both ways
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;
Result1 row · 4 columns
INSTR_SAYSSUBSTR_SAYSINSTR_IS_NULLSUBSTR_IS_NULL
0NULLFALSETRUE

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.

FunctionPattern not foundShown in
REGEXP_REPLACEthe input, unchangedWhat happens if we leave the replacement out?
REGEXP_SUBSTRNULLWhat do we get when it finds nothing?
REGEXP_INSTR0the grid directly above
REGEXP_COUNT0What 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.

Query
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;
Result1 row · 4 columns
DEFAULT_OPTIONOPTION_0_STARTOPTION_1_AFTERSECOND_OCCURRENCE
3355

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.

When option 1 earns its keep

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.

Query
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;
Result8 rows · 4 columns
ROW_IDREGION_TXTCOUNTRYAREA
1us-eastUSEAST
2US-EASTUSEAST
3ca-westCAWEST
4CA-WestCAWEST
5eu-centralEUCENTRAL
6us-eastUSEAST
7US-EastUSEAST
8uk-northUKNORTH

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?

Query — did it work 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;
Result1 row · 3 columns
ROWS_TOTALCOUNTRY_FOUNDAREA_FOUND
888

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.

Query — MINUS as an assertion
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;
Result0 rows · 2 columns
ROW_IDC

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.

Query
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;
Result8 rows · 4 columns
ROW_IDAMOUNT_TXTKEEP_DIGITS_AND_DOTAS_NUMBER
1$4,200.004200.004200.00
2890.50890.50890.50
3$6,15061506150.00
42,310.752310.752310.75
5N/ANULL
6$640.00640.00640.00
79,250.009250.009250.00
8$1,08010801080.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.

Query — the row that is not a number
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';
Result1 row · 4 columns
AMOUNT_TXTCLEANEDCLEANED_LENAS_NUMBER
N/A0NULL

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.

The same NULL, arrived at differently

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.

Query
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;
Result1 row · 6 columns · scroll →
EMAILFIRST_FROM_EMAILLAST_FROM_EMAILAT_SIGN_ATLOCAL_PARTSWAPPED
aisha.khan@example.comaishakhan11aisha.khankhan.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_REPLACE replaces every match by default. The optional arguments are position then occurrence, and occurrence 0 means every match, not none.
  • Leave the replacement out and REGEXP_REPLACE deletes, exactly like the two-argument REPLACE.
  • Capture groups are the reason to prefer it to REPLACE. \\1, \\2 and \\3 in the replacement give back what you matched, so a value can be reordered in one expression. \\0 is the whole match, and a group that did not match becomes an empty string rather than NULL.
  • When the pattern misses, REGEXP_REPLACE returns your input unchanged. No error, no NULL, 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_SUBSTR returns NULL when it finds nothing, and comparing that NULL to '' gives NULL rather than FALSE. A WHERE clause written that way silently matches nothing.
  • REGEXP_INSTR returns 0 for the same absent pattern, and REGEXP_COUNT returns 0 too. 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 be e. The c flag honours the group number too, and with no parameters at all you silently get the whole match instead.
  • REGEXP_INSTR's return option 1 gives the position just past the match, which is already the right starting point for a SUBSTR.
  • Regular expressions and the plain string functions should agree. MINUS against the SPLIT_PART version returned no rows for the country code, which is how you prove a rewrite changed nothing. One MINUS proves one column.
Next in this series

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.