Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim integer from a string

There is a Trim function that I can trim a specific character, but I was wondering if it could trim integers.

I have a list of strings:

'ABC01'
'ABCD02'
'AB5123'

Length and number are irregular. After I run a SQL command, I would like to get this:

'ABC'
'ABCD'
'AB'
like image 235
sayhaha Avatar asked Jul 17 '26 15:07

sayhaha


1 Answers

I would use the translate function. The REGEXP functions in Oracle tend to be CPU hogs compared to the simpler text processing functions.

select translate(string, 'A1234567890', 'A')
from t;

The "A" at the beginning of the second parameter, and matching A for the last parameter translates "A"s to "A"s, doing nothing, but without something in the third parameter string, ORACLE will return null.

EDIT Simple test case

SQL> create table t (string varchar2(100));
Table created.
SQL> insert into t values ('ABC01');
1 row created.
SQL> insert into t values ('ABCD02');
1 row created.
SQL> insert into t values ('AB5123');
1 row created.
SQL> insert into t values ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  2      || 'abcdefghijklmnopqrstuvwxyz1234567890');
1 row created.
SQL> insert into t values ('123AB456');
1 row created.
SQL> insert into t values ('!Whatever!1');
1 row created.
SQL> commit;
Commit complete.

SQL> select translate(string, 'A1234567890', 'A')
  2  from t;

TRANSLATE(STRING,'A1234567890','A')
---------------------------------------------------
ABC
ABCD
AB
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz
AB
!Whatever!

6 rows selected.
like image 122
Shannon Severance Avatar answered Jul 20 '26 07:07

Shannon Severance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!