Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the count of characters and numbers in a string

Tags:

sql

oracle

Hi I have a table test as below

NAME
---------
abc1234
XYZ12789
a12X8b78Y9c5Z

I try to find out the count of number of numbers and characters in the string as

select name,length(replace(translate(lower(name),'abcdefghijklmnopqrstuvwxyz',' '),'      ','')) as num_count,
length(replace(translate(name,'1234567890',' '),' ','')) as char_count
from test6;

Its executing fine giving the output

NAME    NUM_COUNT   CHAR_COUNT
abc1234         4       3
XYZ12789        5       3
a12X8b78Y9c5Z   7       6

But my question is there any option by not giving the abcdefghijklmnopqrstuvwxyz and 1234567890 manually

like image 372
Aspirant Avatar asked Jul 08 '12 02:07

Aspirant


People also ask

Which function is used to count the number of characters in a string?

When you need to count the characters in cells, use the LEN function—which counts letters, numbers, characters, and all spaces.

How do you count the number of characters in a string in Python?

In Python, you can get the length of a string str (= number of characters) with the built-in function len() .


2 Answers

@alfasin answer is good, but if you're using 11g then it can get simpler:

select name,
REGEXP_count(name,'\d') as num_count,
REGEXP_count(name,'[a-zA-Z]') as char_count,
from test6;
like image 190
A.B.Cade Avatar answered Oct 20 '22 00:10

A.B.Cade


If I understand correctly you are using Oracle PLSQL, and as far as I know, there isn't any "built-in" method (in PLSQL) that counts the number of digits/characters in a string.

But, you can do the following to count characters:
select LENGTH(REGEXP_REPLACE('abcd12345','[0-9]')) from dual

and digits:
select LENGTH(REGEXP_REPLACE('abcd12345','[a-zA-Z]')) from dual

Or, in your case:

select name,
LENGTH(REGEXP_REPLACE(name,'[a-zA-Z]','')) as num_count,
LENGTH(REGEXP_REPLACE(name,'[0-9]','')) as char_count,
from test6;

For Bill the Lizard:
My answer was tested on Oracle 11g and it works just fine!
If you decide to delete my answer again, please be kind enough to add a comment that explains why. I was also looking for you in the chat rooms...

like image 38
Nir Alfasi Avatar answered Oct 19 '22 22:10

Nir Alfasi