Alex Rivera | Logout

Use regexp_instr to get the last number in a string

Asked 2012-03-18T03:06:59.190
9

If I used the following expression, the result should be 1.

regexp_instr('500 Oracle Parkway, Redwood Shores, CA','[[:digit:]]')

Is there a way to make this look for the last number in the string? If I were to look for the last number in the above example, it should return 3.

Edit
Report

1 Answer

10

If you were using 11g, you could use regexp_count to determine the number of times that a pattern exists in the string and feed that into the regexp_instr

regexp_instr( str,
              '[[:digit:]]',
              1,
              regexp_count( str, '[[:digit:]]')
            )

Since you're on 10g, however, the simplest option is probably to reverse the string and subtract the position that is found from the length of the string

length(str) - regexp_instr(reverse(str),'[[:digit:]]') + 1

Both approaches should work in 11g

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select '500 Oracle Parkway, Redwood Shores, CA' str
  3      from dual
  4  )
  5  select length(str) - regexp_instr(reverse(str),'[[:digit:]]') + 1,
  6         regexp_instr( str,
  7                       '[[:digit:]]',
  8                       1,
  9                       regexp_count( str, '[[:digit:]]')
 10                     )
 11*   from x
SQL> /

LENGTH(STR)-REGEXP_INSTR(REVERSE(STR),'[[:DIGIT:]]')+1
------------------------------------------------------
REGEXP_INSTR(STR,'[[:DIGIT:]]',1,REGEXP_COUNT(STR,'[[:DIGIT:]]'))
-----------------------------------------------------------------
                                                     3
                                                                3
answered 2012-03-18T03:26:31.993

Your Answer