I have a table with column as strings.
The requirement is to extract last 4 Numeric digits.
The issue is the string is very dynamic and numbers are at different positions.
In this case: (\d{4})"}} regex also won’t work since it is last 4 as per position but in my case it is dynamic string.
Sample Data:
| Value | Expected result |
|---|---|
| 12345689 | 6789 |
| 21-34-567 | 4567 |
| 2150-X1234-YZ | 1234 |
| 21-22-93-001 | 3001 |
Create table regex_string Add Value vachar2(100);
Insert into table regex_string values('123456789');
Insert into table regex_string values('21-34-567');
Insert into table regex_string values('2150-X1234-YZ');
Insert into table regex_string values('21-22-93-001');
>Solution :
We can approach this by first doing a regex replacement to remove all non digit characters. Then take a simple substring of the last 4 digits:
SELECT SUBSTR(REGEXP_REPLACE(val, '[^0-9]+', ''), -4) AS last_four
FROM regex_string;