Ekonomism
Ekonomism

Reputation: 1

Empty answer if an initial zero is not found

When I run a regex trying to remove an initial zero from a number as in the example I get the correct answer if there is a zero before the number. However, if there are no zeroes I get an empty string.

This is not the expected result for me, but might be the way things work.

I would like to have an expression that keeps the string intact if there are no initial zeroes.

This is MRI Ruby 2.6.1

Example 1

string = "0067 more text"
puts string[0..3].sub!(/^0+/, "")
#=> 67

Example 2

string = "6776 more text"
puts string[0..3].sub!(/^0+/, "")
#=> 'empty string'

In Example 2 I would like it to keep the string intact. I wouldn't a priori expect the expression to delete the string. But if it is the correct behaviour I need a way to make it keep the original string intact.

Upvotes: 0

Views: 80

Answers (2)

Ry-
Ry-

Reputation: 224904

sub! does keep the string intact if there’s no match. It just returns nil. If you don’t need to do the operation in place, use the non-mutating String#sub:

puts string[0..3].sub(/^0+/, "")

If you do want the replacement done in place, you’ll be holding onto the string in practice, and it’ll work fine:

s = string[0..3]
s.sub!(/^0+/, "")
puts s

Relevant documentation for sub!:

sub!(pattern, replacement) → str or nil
sub!(pattern) {|match| block } → str or nil

Performs the same substitution as #sub in-place.

Returns str if a substitution was performed or nil if no substitution was performed.

Upvotes: 1

demir
demir

Reputation: 4709

You can use match method instead of sub!

match(/[^0]\d+/)

string = "0067 more text"
puts string[0..3].match(/[^0]\d+/)
#=> 67

string = "6776 more text"
puts string[0..3].match(/[^0]\d+/)
#=> 6776

Upvotes: 0

Related Questions