Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract last 4 numeric digits from string in sql oracle

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading