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

前端 未结 5 1749
旧时难觅i
旧时难觅i 2020-12-11 02:27

I have below string:

ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence

So I want to select Sentence since it is the string a

相关标签:
5条回答
  • 2020-12-11 03:04

    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 ...
    
    0 讨论(0)
  • 2020-12-11 03:06

    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
    0 讨论(0)
  • 2020-12-11 03:12

    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
    
    0 讨论(0)
  • 2020-12-11 03:12
    select 
      substr(
        'ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence',  
        INSTR(
          'ThisSentence.ShouldBe.SplitAfterLastPeriod.Sentence',
          '.',
          -1
        )+1
      ) 
    from dual;
    
    0 讨论(0)
  • 2020-12-11 03:15

    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;
    
    0 讨论(0)
提交回复
热议问题