Say I have a table column that has results like:
ABC_blahblahblah
DEFGH_moreblahblahblah
IJKLMNOP_moremoremoremore
I would like to be able to write a query that selects this column from said table, but only returns the substring up to the Underscore (_) character. For example:
ABC
DEFGH
IJKLMNOP
The SUBSTRING function doesn't seem to be up to the task because it is position-based and the position of the underscore varies.
I thought about the TRIM function (the RTRIM function specifically):
SELECT RTRIM('listofchars' FROM somecolumn)
FROM sometable
But I'm not sure how I'd get this to work since it only seems to remove a certain list/set of characters and I'm really only after the characters leading up to the Underscore character.
This can be done using REGEXP_SUBSTR easily.
Please use
where STRING_EXAMPLE is your string.
Try:
It will solve your problem.
Using a combination of SUBSTR, INSTR, and NVL (for strings without an underscore) will return what you want:
Result:
Use:
Reference:
Addendum
If using Oracle10g+, you can use regex via REGEXP_SUBSTR.
You need to get the position of the first underscore (using INSTR) and then get the part of the string from 1st charecter to (pos-1) using substr.
Instr documentation
Susbtr Documentation
is the right answer, as posted by user1717270
If you use
INSTR
, it will give you the position for a string that assumes it contains "_" in it. What if it doesn't? Well the answer will be 0. Therefore, when you want to print the string, it will print aNULL
. Example: If you want to remove the domain from a "host.domain". In some cases you will only have the short name, i.e. "host". Most likely you would like to print "host". Well, withINSTR
it will give you aNULL
because it did not find any ".", i.e. it will print from 0 to 0. WithREGEXP_SUBSTR
you will get the right answer in all cases:HOST
and
HOST
To find any sub-string from large string:
Then to find the string
'Ple'
fromString_value
we can do as:You will find result:
Ple
Remember this if all your Strings in the column do not have an underscore (...or else if null value will be the output):