JoshReedSchramm
JoshReedSchramm

Reputation: 2761

Add 0 padding to number in middle of string in ruby

This may be a really simple regex but its one of those problems that have proven hard to google.

I have error codes coming back from a third party system. They are supposed to be in the format:

ZZZ##

where Z is Alpha and # is numeric. They are supposed to be 0 padded, but i'm finding that sometimes they come back

ZZZ#

without the 0 padding.

Anyone know how i could add the 0 padding so i can use the string as an index to a hash?

Upvotes: 1

Views: 878

Answers (4)

pguardiario
pguardiario

Reputation: 54984

Here's mine:

"ZZZ7".gsub(/\d+/){|x| "%02d" % x}
=> "ZZZ07"

Upvotes: 1

ashoda
ashoda

Reputation: 2840

There's probably a million ways to do this but here's another look.

str.gsub!(/[0-9]+/ , '0\0' ) if str.length < 5

Upvotes: 0

Phrogz
Phrogz

Reputation: 303253

fixed = str.gsub /([a-z]{3})(\d)(?=\D|\z)/i, '\10\2'

That says:

  • Find three letters
    • …followed by a digit
    • …and make sure that then you see either a non-digit or the end of file
  • and replace with the three letters (\1), a zero (0), and then the digit (\2)

To pad to an arbitrary length, you could:

# Pad to six digits
fixed = str.gsub /([a-z]{3})(\d+)/i do
  "%s%06d" % [ $1, $2.to_i ]
end

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

Here's my take:

def pad str
  number = str.scan(/\d+/).first
  str[number] = "%02d" % number.to_i
  str
end

6.times do |n|
  puts pad "ZZZ#{7 + n}"
end

# >> ZZZ07
# >> ZZZ08
# >> ZZZ09
# >> ZZZ10
# >> ZZZ11
# >> ZZZ12

Reading:

Upvotes: 3

Related Questions