简体   繁体   中英

counting length of number and character inside string using regex in ruby

how to counting length of number and character inside string using regex in ruby? if i have some case like this, how to resolve it? example :

abc = "12345678a"

after counting using regex, i want get result like this :

number = 8
char = 1

how to do that?

Try following

abc = "12345678a"
abc.scan(/\d/).length
# => 8 
abc.scan(/\D/).length
# => 1 

No regex:

abc = "12345678a"
p abc.count("0-9") # => 8
p abc.count("a-zA-Z") # => 1

This is an optional, but I still think regex is better.

irb(main):051:0> number, char = abc.bytes.to_a.partition { |e| e >= 48 and e <= 57}
=> [[49, 50, 51, 52, 53, 54, 55, 56], [97]]
irb(main):053:0> number.count
=> 8
irb(main):054:0> char.count
=> 1

partition: Returns two arrays, the first containing the elements of enum for which the block evaluates to true, the second containing the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM