简体   繁体   中英

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

I have below string:

ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence

So I want to select Sentence since it is the string after the last period. How can I do this?

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

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;
select 
  substr(
    'ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence',  
    INSTR(
      'ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence',
      '.',
      -1
    )+1
  ) 
from dual;

The INSTR function accepts a third parameter, the occurrence. It defaults to 1 (the first occurrence), but also accepts negative numbers (meaning counting from the last occurrence backwards).

select substr(str, instr(str, '.', -1) + 1)
from (
    select 'ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence'
           as str
    from dual);

Sentence

how many dots in a string?

select length(str) - length(replace(str, '.', '') number_of_dots from ...

get substring after last dot:

select substr(str, instr(str, '.', 1, number_of_dots)+1) from ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM