Last word in a sentence: In SQL (regular expressions possible?)

后端 未结 5 1469
夕颜
夕颜 2020-12-19 14:32

I need this to be done in Oracle SQL (10gR2). But I guess, I would rather put it plainly, any good, efficient algorithm is fine.

Given a line (or sentence, containing

相关标签:
5条回答
  • 2020-12-19 14:41

    this leaves the punctuation but gets the final word

    with datam as (
    SELECT 'abc asdb.' A FROM DUAL UNION
    select 'ipso factum' a from dual union
    select 'ipso factum' a from dual union
    SELECT 'ipso factum2' A FROM DUAL UNION
    SELECT 'ipso factum!' A FROM DUAL UNION
    SELECT 'ipso factum  !' A FROM DUAL UNION
    SELECT 'ipso factum/**//*/?.?' A FROM DUAL UNION
    SELECT 'ipso factum  ...??!?!**' A FROM DUAL UNION
    select 'ipso factum ..d.../.>' a from dual 
    
    )
    SELECT a,
    --REGEXP_SUBSTR(A, '[[:alnum:]]_+$', 1, 1, 'c') , /** these are the other examples*/
    --REGEXP_SUBSTR(A, '\S+$') ,  /** these are the other examples*/
    regexp_substr(a, '[a-zA-Z]+[^a-zA-Z]*$')  
    
    from datam
    
    0 讨论(0)
  • 2020-12-19 14:44

    I'm not sure if you can use a regex in oracle, but wouldn't

    (\w+)\W*$

    work?

    0 讨论(0)
  • 2020-12-19 14:46

    Not sure how it is performance wise, but this should do it:

    select regexp_substr(&p_word_in, '\S+$') from dual;
    
    0 讨论(0)
  • 2020-12-19 14:50

    This regex matches the last word on a line:

    \w+$
    

    And RegexBuddy gives this code for use in Oracle:

    DECLARE
            match VARCHAR2(255);
    BEGIN
            match := REGEXP_SUBSTR(subject, '[[:alnum:]]_+$', 1, 1, 'c');
    END;
    
    0 讨论(0)
  • 2020-12-19 14:51

    I reckon it's simpler with INSTR/SUBSTR:

    WITH q AS (SELECT 'abc def ghi' AS sentence FROM DUAL)
    SELECT SUBSTR(sentence, INSTR(sentence,' ',-1) + 1)
    FROM q;
    
    0 讨论(0)
提交回复
热议问题