Get substring from string db2

Viewed 146

I have 2 strings for exampe:

FO-123-4444-3353-9999-TEXT and
123-4444-3353-88888-something

How can i get substring without TEXT,something on the end and if there is FO also without FO. FO will be always there or won't , but TEXT can have any other word instead

Final result shoul be:

123-4444-3353-88888 and
123-4444-3353-9999
2 Answers

If you want to replace FO- in the beginning and -TEXT in the end, use regexp_replace. It can be done in single regexp using OR (|)

select regexp_replace('FO-123-4444-3353-9999-TEXT','^FO-|-TEXT$','') from SYSIBM.SYSDUMMY1;

Result:

123-4444-3353-9999

This answers the original version of the question.

Assuming that "TEXT" and "FO" do not appear anywhere else in the string (as in your examples), you can use REPLACE():

select replace(replace(col, '-TEXT', ''), 'FO-', '')

For the revised question, you can use regexp_replace():

select regexp_replace(col, '^FO-|-TEXT[0-9]*$', '') 

This assumes that the "FO" and "TEXT" are at the beginning and end of your strings.

Related