Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of zeros at the start of a string

Tags:

regex

ruby

I have a string:

"0011HelloWor00ld001"

How do I count the number of zeros in the starting of the string? For example, the above string should return 2.

I tried .match(/^[0]+/).size but it doesn't work.

like image 700
InQusitive Avatar asked Oct 26 '25 17:10

InQusitive


2 Answers

.match(/^0+/) will return a MatchData object, and thus you get 1 as the result (it denotes the number of elements in the match array).

You need to get the size of the match itself. Use one of the following:

"0011HelloWor00ld001".match(/^0+/)[0].size
"0011HelloWor00ld001"[/^0+/].size
"0011HelloWor00ld001".match(/^0+/).to_s.size
like image 55
Wiktor Stribiżew Avatar answered Oct 29 '25 05:10

Wiktor Stribiżew


You could also simply use the index method of String like

str = '0011HelloWor00ld001'
# as noted by @steenslag if the full string is zeros index will return nil
# solve by returning full string length
str.index(/[^0]/) || str.length 
#=> 2 
like image 41
engineersmnky Avatar answered Oct 29 '25 06:10

engineersmnky



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!