oracle 12c - select string after last occurrence of a character

And yet another way.

Not sure from a performance standpoint which would be best...

The difference here is that we use -1 to count backwards to find the last . when doing the instr.

  With CTE as 
  (Select 'ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence' str, length('ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence') len from dual)
  Select substr(str,instr(str,'.',-1)+1,len-instr(str,'.',-1)+1) from cte;

Just for completeness' sake, here's a solution using regular expressions (not very complicated IMHO :-) ):

select regexp_substr(
  'ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence',
  '[^.]+$') 
from dual

The regex

  • uses a negated character class to match anything except for a dot [^.]
  • adds a quantifier + to match one or more of these
  • uses an anchor $ to restrict matches to the end of the string

You can probably do this with complicated regular expressions. I like the following method:

select substr(str, - instr(reverse(str), '.') + 1)

Nothing like testing to see that this doesn't work when the string is at the end. Something about - 0 = 0. Here is an improvement:

select (case when str like '%.' then ''
             else substr(str, - instr(reverse(str), ';') + 1)
        end)

EDIT:

Your example works, both when I run it on my local Oracle and in SQL Fiddle.

I am running this code:

select (case when str like '%.' then ''
             else substr(str, - instr(reverse(str), '.') + 1)
        end)
from (select 'ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence' as str from dual) t