rahrahruby
rahrahruby

Reputation: 693

ruby regex find and replace

I have the following output:
time = 15:40:32.81

And I want to eliminate : and the . so that it looks like this:
15403281

I tried doing a

time.gsub(/\:\s/,'')

but that didn't work.

Upvotes: 10

Views: 13159

Answers (4)

Jed Schneider
Jed Schneider

Reputation: 14671

"15:40:32.81".gsub(/:|\./, "")

Upvotes: 16

Nakilon
Nakilon

Reputation: 35054

time.delete ':.'

But it'll edit your variable. If you don't want it:

time.dup.delete ':.'

Upvotes: 2

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94123

time = '15:40:32.81'
numeric_time = time.gsub(/[^0-9]+/, '')
# numeric_time will be 15403281

[^0-9] specifies a character class containing any character which is not a digit (^ at the beginning of a class negates it), which will then be replaced by an empty string (or, in other words, removed).

(Updated to replace \d with 0-9 for clarity, though they are equivalent).

Upvotes: 6

todb
todb

Reputation: 329

If you want to be fancy and use an actual time object...

time = Time.now
time.strftime("%H%M%S") + time.usec.to_s[0,2]
# returns "15151788"

Upvotes: 3

Related Questions