Sub topic 11
When to use REGEXP_SUBSTR, REGEXP_INSTR, REGEXP_REPLACE, or TRANSLATE
This chapter assumes you know SUBSTR, INSTR, and REPLACE from the earlier chapters, including 1-based positions, the 0 that INSTR returns for no match, and how an empty string behaves as NULL in Oracle. It also assumes you can read a simple pattern such as [0-9]+. The goal is to help you decide when the plain functions are enough and when a regular expression function or TRANSLATE fits better.
The plain functions and their limits
SUBSTR, INSTR, and REPLACE work on literal text. They match an exact substring and nothing else. That makes them fast, easy to read, and predictable. They struggle when the thing you are looking for is a shape instead of a fixed string:
- "the first run of digits" (the digits differ on every row)
- "the third field, but fields may be separated by commas or semicolons"
- "collapse any number of spaces into one"
- "everything after the last dot, whatever the case"
For these, Oracle provides regular expression (regex) versions of each function. Each regex function takes a pattern instead of a literal search string.
| Literal function | Regex counterpart | Returns when nothing matches |
|---|---|---|
| `SUBSTR` | `REGEXP_SUBSTR` | `NULL` |
| `INSTR` | `REGEXP_INSTR` | `0` |
| `REPLACE` | `REGEXP_REPLACE` | the original string, unchanged |
TRANSLATE is a different tool. It does not use patterns. It maps characters one-for-one.
REGEXP_SUBSTR: extract by pattern
The signature is:
REGEXP_SUBSTR(source, pattern [, position [, occurrence [, match_param [, subexpr]]]])position and occurrence work like the matching arguments of INSTR. match_param holds flags such as 'i' for case-insensitive matching. subexpr returns only one parenthesized group of the match.
Here are three common jobs.
SELECT REGEXP_SUBSTR('report.final.pdf', '[^.]+$') AS extension,
REGEXP_SUBSTR('abc123def456', '[0-9]+') AS first_number,
REGEXP_SUBSTR('a,b,c,d', '[^,]+', 1, 3) AS third_field
FROM dual;
-- extension = 'pdf', first_number = '123', third_field = 'c'The first query replaces the INSTR(..., '.', -1) plus SUBSTR combination with one call. The pattern [^.]+$ means "one or more characters that are not a dot, anchored at the end of the string." The regex functions have no backward search. A negative position is not allowed, so you anchor with $ instead.
To pull out one part of a match, wrap that part in parentheses and give its number as subexpr:
SELECT REGEXP_SUBSTR('[email protected]', '^([^@]+)@(.+)$', 1, 1, NULL, 1) AS username,
REGEXP_SUBSTR('[email protected]', '^([^@]+)@(.+)$', 1, 1, NULL, 2) AS domain,
REGEXP_SUBSTR('Report.PDF', '\.([a-z]+)$', 1, 1, 'i', 1) AS ext_any_case
FROM dual;
-- username = 'user', domain = 'example.com', ext_any_case = 'PDF'The NULL in the fifth position means "no flags." The backslash in \. makes the dot literal. Without it, . matches any character.
The empty-field trap
[^,]+ needs at least one character, so it skips empty fields. In 'a,,c' the second match is c, not an empty value. If field positions matter, match the field together with its delimiter and return only the field:
SELECT REGEXP_SUBSTR('a,,c,d', '([^,]*)(,|$)', 1, 2, NULL, 1) AS second_field,
REGEXP_SUBSTR('a,,c,d', '([^,]*)(,|$)', 1, 3, NULL, 1) AS third_field
FROM dual;
-- second_field = NULL (the field is empty), third_field = 'c'This pattern uses * (zero or more), so an empty field still counts as a match.
REGEXP_INSTR: locate by pattern
The signature is:
REGEXP_INSTR(source, pattern [, position [, occurrence [, return_option [, match_param [, subexpr]]]]])The extra argument is return_option. With 0 (the default) you get the position of the first character of the match. With 1 you get the position just after the match.
SELECT REGEXP_INSTR('abc123def456', '[0-9]+') AS start_pos,
REGEXP_INSTR('abc123def456', '[0-9]+', 1, 1, 1) AS after_match,
REGEXP_INSTR('abc', '[0-9]+') AS no_match
FROM dual;
-- start_pos = 4, after_match = 7, no_match = 0Use REGEXP_INSTR when you need a position that a pattern defines. The return_option of 1 gives you the end of a match without computing start + LENGTH(match). If you only need to know whether a pattern is present, REGEXP_LIKE in a WHERE clause is clearer than testing REGEXP_INSTR(...) > 0.
REGEXP_REPLACE: replace by pattern
The signature is:
REGEXP_REPLACE(source, pattern [, replace_string [, position [, occurrence [, match_param]]]])Two defaults differ from REPLACE. When occurrence is omitted (or 0), all matches are replaced, which is the same as REPLACE. When replace_string is omitted or NULL, the matches are deleted.
SELECT REGEXP_REPLACE('(555) 123-4567', '[^0-9]') AS digits_only,
TRIM(REGEXP_REPLACE(' too many spaces ', ' +', ' ')) AS squeezed
FROM dual;
-- digits_only = '5551234567', squeezed = 'too many spaces'Compare digits_only with the nested REPLACE example from the earlier chapter, where the hyphen survived. A negated character class ([^0-9], "anything that is not a digit") removes every unwanted character without listing each one.
Parenthesized groups can be reused in the replacement as \1 through \9:
SELECT REGEXP_REPLACE('Smith, John', '^(.+), (.+)$', '\2 \1') AS reordered
FROM dual;
-- reordered = 'John Smith'REPLACE cannot do this, because it has no concept of captured text.
TRANSLATE: character-for-character mapping
TRANSLATE(expr, from_string, to_string)TRANSLATE replaces the first character of from_string with the first character of to_string, the second with the second, and so on. It looks at single characters, never at substrings. This is the key difference from REPLACE:
SELECT REPLACE('banana', 'an', 'AN') AS with_replace,
TRANSLATE('banana', 'an', 'AN') AS with_translate
FROM dual;
-- with_replace = 'bANANa', with_translate = 'bANANA'REPLACE changed only the two-character sequence an. TRANSLATE changed every a and every n independently, including the final a.
If to_string is shorter than from_string, the extra characters in from_string are deleted. This gives you a compact way to remove a set of characters without nesting. Because an empty string is NULL in Oracle, you cannot pass '' as to_string. The result of the whole call would be NULL. The usual idiom is a dummy character that maps to itself:
SELECT TRANSLATE('(555) 123-4567', 'x() -', 'x') AS cleaned
FROM dual;
-- cleaned = '5551234567'Here x maps to x, and the parenthesis, space, and hyphen have no counterpart, so they are removed. This replaces the three nested REPLACE calls, and it fixes the case where the hyphen stayed behind.
Choosing between them
The same decision as a table:
| Task | Best fit | Why |
|---|---|---|
| Split at one known delimiter such as `@` | `SUBSTR` + `INSTR` | Simple, fast, easy to read |
| Remove a known word or separator | `REPLACE` | One literal, no pattern syntax |
| Delete or swap a set of single characters | `TRANSLATE` | One call, no nesting |
| Keep only digits, or only letters | `REGEXP_REPLACE` with `[^0-9]` | You describe what to remove by class |
| Find the first run of digits | `REGEXP_SUBSTR` | The length and content vary |
| Nth field when delimiters vary | `REGEXP_SUBSTR` | The pattern covers both delimiters |
| Reorder parts of a string | `REGEXP_REPLACE` with `\1`, `\2` | Captured groups |
| Case-insensitive search | Regex with `'i'` | The plain functions are case-sensitive |
Costs and gotchas
- Speed. The regex functions do more work per row than the plain ones, and on large tables the difference can matter. When a literal function does the job, prefer it.
- Escaping. Characters such as
. * + ? ( ) [ ] { } | ^ $ \have special meaning in a pattern. To match them literally, put a backslash before them, as in\.. Forgetting this is the most common regex bug. - Greedy matching.
+and*match as much as they can. In'<b>x</b>', the pattern<.+>matches the whole string. The non-greedy form<.+?>stops at the first>. - Missing features. Oracle regular expressions have no lookahead or lookbehind. Shorthand classes such as
\d,\w, and\sexist in recent releases, but[0-9]or[[:digit:]]is the more portable spelling. NULLrules carry over.REGEXP_SUBSTRreturnsNULLfor no match, so an unguardedLENGTH(REGEXP_SUBSTR(...))also returnsNULLfor those rows. Wrap the call inNVLorCOALESCEif you need a default.- Readability. A long pattern is hard for the next reader to maintain. If a task needs three nested
SUBSTR/INSTRcalls with+ 2arithmetic, a pattern with a captured group is often clearer. If the pattern needs a comment to be understood, a literal approach may be better.
Using regex functions in WHERE and UPDATE
These functions work wherever an expression is allowed. For testing a pattern in a filter, REGEXP_LIKE is the condition form:
SELECT zip
FROM (SELECT '12345' AS zip FROM dual
UNION ALL SELECT '1234A' FROM dual
UNION ALL SELECT '123456' FROM dual)
WHERE REGEXP_LIKE(zip, '^[0-9]{5}$');
-- returns only '12345'For cleanup, an UPDATE can apply REGEXP_REPLACE or TRANSLATE in the SET clause. As with any bulk edit, run the same expression in a SELECT first and check the output before you change data.
Exercise
A column contains values such as 'A1-B2_C3'. Write one expression that keeps only the letters (result 'ABC'), and name one alternative that does not use a regular expression.
Show answer
REGEXPREPLACE(col, '[^A-Za-z]') removes everything that is not a letter, so 'A1-B2C3' becomes 'ABC'. A non-regex alternative is TRANSLATE(col, 'x0123456789-_', 'x'), which deletes the digits, hyphen, and underscore. It only works if you can list every unwanted character, so it fails for unexpected input such as '#'.
Exercise
What does TRANSLATE('abc', 'abc', '') return, and how do you rewrite the call so that it deletes 'a' and 'b' and keeps 'c'?
Show answer
It returns NULL, because Oracle treats '' as NULL and TRANSLATE returns NULL when an argument is NULL. Use a dummy character that maps to itself: TRANSLATE('abc', 'xab', 'x') returns 'c'.
Exercise
For the string 'a,,c', REGEXP_SUBSTR('a,,c', '[^,]+', 1, 2) returns 'c'. Why does it not return an empty value for the second field, and which pattern keeps the empty field?
Show answer
The pattern [^,]+ needs at least one non-comma character, so the empty field between the two commas is never a match, and the second match is 'c'. The pattern ([^,]*)(,|$) with subexpr 1 allows zero characters, so occurrence 2 returns the empty field, which Oracle reports as NULL.