boogiewonder
boogiewonder

Reputation: 145

changing two (unknown) dates inside a file using regex

I am trying to change a file with two (unknown) dates in format: YYYY-MM-DD or YYYY-M-D to two different specified dates. I can get one date change to work, or all dates changed to a single new date but I can't get the first encountered date to change to the 1st specified date, and the second to it's specified date. To illustrate:

Text file example:
text etc text
etc text 2015-09-04
text etc text
2015-8-2

I have the following script:

line = File.read("test.txt")

    new_contents = line.gsub(/^\d{4}-\d{2}-\d{2}/,'2016-10-10')

    puts new_contents

File.open("test.txt", "w") {|file| file << new_contents }

This works, but only for one date change. I've tried just doubling up the script, and inserting a repeat of the above inside a "do loop" but it always changes both dates to the second specified date. Does anyone know where to look for an answer?

Also is there some way to specify either YYYY-MM-DD or YYYY-M-D?

Update: So I'm at this stage I have this code:

line = File.read("test.txt")
  new_contents = line.gsub(/(\d{4}-\d{2}-\d{2})|(\d{4}-\d{1}-\d{1})/) {$1 ? '2016-10-10':'9999-9-9'}
  puts new_contents

So nearly there but it seems to give random orders for the results. sometimes 2016-10-10 is first, sometimes second. Sometimes they are both 9999-9-9 It's a bit strange. I've tried reversing the values but the results are the same.

example to make it 100% clear (hopefully). Change dates to 2014-10-10 and 2014-11-11 ORGINAL:

lorem ipsum 1111-1-1 
lorem 1111-1-1

RESULT:

lorem ipsum 2014-10-10
lorem 2014-11-11

Example 2; Change dates to 2014-6-6 and 2014-11-11

ORIGINAL:

lorem ipsum 2014-10-10
lorem 2015-12-12

RESULT:

lorem ipsum 2014-6-6
lorem 2014-11-11

Upvotes: 1

Views: 78

Answers (1)

Stephan
Stephan

Reputation: 43043

Try this instead:

line.gsub(/(\d{4}-\d{2}-\d{2})|(\d{4}-\d{1}-\d{1})/) {$1 ? '2016-10-10':'9999-9-9'}

Replace '9999-9-9' with your second date.

gsub accepts an optional block. It will replace any match with the result of that block.

DESCRIPTION

Regular expression visualization

DEMO

Regex: http://rubular.com/r/KgSypeaKRu
Ruby code: https://code.hackerearth.com/caa872Q

SAMPLE CODE

print "2015-09-04".gsub(/(\d{4}-\d{2}-\d{2})|(\d{4}-\d{1}-\d{1})/) {$1 ? '2016-10-10':'9999-9-9'}
print "\n"
print "2015-7-7".gsub(/(\d{4}-\d{2}-\d{2})|(\d{4}-\d{1}-\d{1})/) {$1 ? '2016-10-10':'9999-9-9'}

OUTPUT

2016-10-10
9999-9-9

EDIT If you want to do custom replacements, here is an example:

lines.gsub(/(\d{4}-\d{2}-\d{2})|(\d{4}-\d{1}-\d{1})/) {
    if $1
       # YYYY-MM-DD
       # Do some replacements or not...
    else 
       # YYYY-M-D
       # Do other replacements...
    end
}

Please refer to the gsub documentation for any details.

Upvotes: 1

Related Questions