string formatting, remove leading chars

I have a string like this: 00:11:40 or 00:02:40 how do I formated so that I can always get rid of the leading zero(s) and colon(s), so it looks like this 11:40 or 2:40

Answers


We call these "leading" characters, not trailing, since they're at the beginning, but the regex for this is very easy

x.sub(/^[0:]*/,"")

That works exactly as you phrased it: starting at the beginning of the string, remove all the 0s and :s.


You can use something like Peter said, but would correctly be:

s = "00:11:40"
s = s[3..-1]   # 11:40

Another approach would be to use the split method:

s = "00:11:40".split(":")[1,2].join(":")

Although I find that one more confusing and complex.


EDIT: the OP wanted this from the beginning:

seconds = 11*60+40
Time.at(seconds.to_i).gmtime.strftime('%M:%S')  # gives '11:40'

or see man strftime for more formatting options.

EDIT: incorporating all the discussion, here's the recommended approach. It removes the need for the Time call as well.

seconds = seconds.to_i
if seconds >= 60
  "#{seconds/60}:#{seconds%60}"
else
  "#{seconds}"
end

You might want to try positive look-behind regex. Nice reference

it "should look-behind for zeros" do
time = remove_behind_zeroes("ta:da:na")
time.should be_nil

time = remove_behind_zeroes("22:43:20")
time.should == "22:43:20"

time = remove_behind_zeroes("00:12:30")
time.should == "12:30"

time = remove_behind_zeroes("00:11:40")
time.should == "11:40"

time = remove_behind_zeroes("00:02:40")
time.should == "2:40"

time = remove_behind_zeroes("00:00:26")
time.should == "26"

end

def remove_behind_zeroes(value)
exp = /(?<=00:00:)\d\d/
match = exp.match(value)
if match then return match[0] end

exp = /(?<=00:0)\d:\d\d/
match = exp.match(value)
if match then return match[0] end

exp = /(?<=00:)\d\d:\d\d/
match = exp.match(value)
if match then return match[0] end

exp = /\d\d:\d\d:\d\d/
match = exp.match(value)
if match then return match[0] end
nil

end


A lot of the times you can simply rely on basic conversion techniques, in ruby for example, if you had a string like "05" and wanted it to just be 5, you'd simply do "05".to_i


Need Your Help

Does Silverlight support StringFormat in binding?

silverlight data-binding

I know that WPF 3.5 SP1 supports a StringFormat in a binding, but can Silverlight do the same? I thought it could, but damned if I can make it work!

PHPUnit : Fatal error handling

php error-handling phpunit fatal-error

I use PHPUnit for unit tests, but when a fatal error is triggered, the script dies and I have no correct PHPUnit output.