ggn
ggn

Reputation: 25

Reformatting dates

I'm trying to reformat German dates (e.g. 13.03.2011 to 2011-03-13).

This is my code:

str = "13.03.2011\n14:30\n\nHannover Scorpions\n\nDEG Metro Stars\n60\n2 - 3\n\n\n\n13.03.2011\n14:30\n\nThomas Sabo Ice Tigers\n\nKrefeld Pinguine\n60\n2 - 3\n\n\n\n"
str = str.gsub("/(\d{2}).(\d{2}).(\d{4})/", "/$3-$2-$1/")

I get the same output like input. I also tried my code with and without leading and ending slashes, but I don't see a difference. Any hints?

I tried to store my regex'es in variables like find = /(\d{2}).(\d{2}).(\d{4})/ and replace = /$3-$2-$1/, so my code looked like this:

str = "13.03.2011\n14:30\n\nHannover Scorpions\n\nDEG Metro Stars\n60\n2 - 3\n\n\n\n13.03.2011\n14:30\n\nThomas Sabo Ice Tigers\n\nKrefeld Pinguine\n60\n2 - 3\n\n\n\n" 
find = /(\d{2}).(\d{2}).(\d{4})/
replace = /$3-$2-$1/
str = str.gsub(find, replace)

TypeError: no implicit conversion of Regexp into String
    from (irb):4:in `gsub'

Any suggestions for this problem?

Upvotes: 1

Views: 854

Answers (1)

Sabuj Hassan
Sabuj Hassan

Reputation: 39355

First mistake is the regex delimiter. You do not need place the regex as string. Just place it inside a delimiter like //

Second mistake, you are using captured groups as $1. Replace those as \\1

str = str.gsub(/(\d{2})\.(\d{2})\.(\d{4})/, "\\3-\\2-\\1")

Also, notice I have escaped the . character with \., because in regex . means any character except \n

Upvotes: 1

Related Questions