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

I need this to be done in Oracle SQL (10gR2). But, I think, I would say that any good, efficient algorithm is fine.

If you specified a string (or a sentence containing one or more words, English), how do you find the last word of the sentence?

Here is what I tried in SQL. But I would like to see an effective way to do this.

select reverse(substr(reverse(&p_word_in) , 0 , instr(reverse(&p_word_in), ' ') ) ) from dual; 

The idea was to swap the string, find the first counter space, get the substring and change the string. Is it effective enough? Is regex available? I am on Oracle 10g R2. But I do not mind any attempts in another programming language, but I will not write a PL / SQL function if necessary.

Update:

Jeffrey Kemp gave a wonderful answer. It works great.

Answer

 SELECT SUBSTR(&sentence, INSTR(&sentence,' ',-1) + 1) FROM dual 
+4
source share
5 answers

I find this easier with INSTR / SUBSTR:

 WITH q AS (SELECT 'abc def ghi' AS sentence FROM DUAL) SELECT SUBSTR(sentence, INSTR(sentence,' ',-1) + 1) FROM q; 
+6
source

Not sure how reasonable this is, but this should do it:

 select regexp_substr(&p_word_in, '\S+$') from dual; 
+2
source

I'm not sure you can use regex in oracle, but not

(\ W +) \ W * $

Job?

+1
source

This regular expression matches the last word in a string:

 \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
source

it leaves punctuation but gets the last 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
source

All Articles