Home » SQL & PL/SQL » SQL & PL/SQL » How do I extract last element of a string?
( ) 1 Vote
|
|
|
|
Re: How do I extract last element of a string? [message #199689 is a reply to message #199682] |
Wed, 25 October 2006 20:38   |
 |
ebrian
Messages: 2794 Registered: April 2006
|
Senior Member |
|
|
Regular expressions are definitely not an intuitive concept.
The '?' in my first regex can actually be removed and simplified to regexp_substr(id,'[^ ]*$').
To explain the expression, I'll start from the right hand side of the expression '[^ ]*$'. The '$' indicates to match from the end of the string. The '*' matches zero or more of the expression [^ ], which is essentially stating match as many non-space characters as possible. When a '^' is used inside a bracket expression, it is used to indicate negation. In this case it means anything EXCEPT a space. Therefore, when the first space from the right is encountered, the search stops and returns everything from the end of the string to right before the search stopped. The search will stop when the first space is encountered or if the end of the string is reached prior to a hitting a space (ie. no spaces are in the text). When NO space is encountered, then everything is returned, as indicated in the word 'foo' by itself.
Good job with your expression. Like mine above, yours can be further simplified to regexp_substr(id,'[^ ]*'). Doesn't really hurt anything to include the leading '^', but as you see below, it works without it too:
SQL> with list as (
2 select 'foo' id from dual union all
3 select 'foo bar' from dual union all
4 select 'foo bar moo' from dual)
5 select regexp_substr(id,'^[^ ]*'),
6 regexp_substr(id,'[^ ]*') from list;
REGEXP_SUBS REGEXP_SUBS
----------- -----------
foo foo
foo foo
foo foo
By default, the search will begin from the left of the string (unless a '$' is used as explained above). Therefore, '[^ ]*' indicates to start from the beginning of the string and match as many non-space characters as possible. Once a space (or the end of the string) is encountered, the search will stop.
HTH
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Goto Forum:
Current Time: Wed May 21 06:21:17 CDT 2025
|