1

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?

2
  • How many zeroes do you want to add? Just one? Commented Apr 30, 2012 at 23:55
  • sorry ya. it should match that ZZZ## format Commented Apr 30, 2012 at 23:55

4 Answers 4

3

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:

Sign up to request clarification or add additional context in comments.

Comments

2
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

1 Comment

On SO you learn every day. :) Thank you, sir, for this neat trick with gsub and block :)
1

Here's mine:

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.