Dimitri de Ruiter
Dimitri de Ruiter

Reputation: 745

Rails - regex to find specific date

In app I build to learn rails, I am working on finding data. Now I have this case: in this text, I want to find the right delivery date.

"delivery date 01/12/2015 delivery note 30112016 invoice date 03.01.2016"

The regex I made get all the dates:

[0-9]{1,2}[-.\/][0-9]{1,2}[-.\/][0-9]{2,4}

How to add the condition that it picks the date preceded "delivery date"?

Upvotes: 1

Views: 140

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

Add delivery date to the pattern and capture the date:

s[/delivery date\s*(\d{1,2}[-.\/]\d{1,2}[-.\/]\d{2,4})/, 1]

See the online Ruby demo

The 1 argument tells Ruby to only fetch the contents captured within the first capturing group now.

Just in case you are interested in dates that have consistent separators, you may consider using

/delivery date\s*(\d{1,2}([-.\/])\d{1,2}\2\d{2,4})/
                         ^^^^^^^^       ^^

where the separator is captured into Group 2 and the value is re-used later with the backreference \2.

Upvotes: 1

Related Questions