Reputation: 1276
In Oracle pl/sql, how do I retrieve only numbers from string.
e.g. 123abc -> 123 (remove alphabet)
e.g. 123*-*abc -> 123 (remove all special characters too)
Upvotes: 0
Views: 9546
Reputation: 627469
If you need to extract the first occurrence of one or more digits, you may simply use a REGEXP_SUBSTR
:
SELECT REGEXP_SUBSTR('123*-*abc','\d+') from dual
\d+
here is NOT equal to [0-9]+
as it also matches any Unicode digit characters (like ۱۲۳۴۵۶۷۸۹
).
See the DB fiddle demo:
Cf. \d
vs [0-9]
:
SELECT REGEXP_SUBSTR('۱۲۳۴۵۶۷۸۹ 123*-*abc','\d+') from dual
-- > ۱۲۳۴۵۶۷۸۹
Tested in Oracle 23c.
Upvotes: 0
Reputation: 15493
Several options, but this should work:
select regexp_replace('123*-*abc', '[^[:digit:]]', '') from dual
This removes all non-digits from the input.
If using in pl/sql, you could do an assignment to a variable:
declare
l_num number;
l_string varchar2(20) := '123*-*abc';
begin
l_num := regexp_replace(l_string, '[^[:digit:]]', '');
dbms_output.put_line('Num is: ' || l_num);
end;
Output:
Num is: 123
Upvotes: 1
Reputation: 13527
Try this:
select regexp_replace(value, '[A-Za-z]') from dual;
Upvotes: 0