简体   繁体   English

使用Ruby中的正则表达式计算字符串内数字和字符的长度

[英]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? 如何在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. partition:返回两个数组,第一个包含该块求值为true的enum元素,第二个包含其余元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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