Reputation: 2761
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
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
Reputation: 303253
fixed = str.gsub /([a-z]{3})(\d)(?=\D|\z)/i, '\10\2'
That says:
\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
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