0

I try to write a regex for a date pattern (mm/dd/yyyy ; m/d/yy ; etc...) :

    ".*([0-9]+/[0-9]+/[0-9]+).*"

However for my usecase, the year can be omitted. In this case, I still want to match mm/dd. I tried to put the last group opional for that purpose:

    ".*([0-9]+/[0-9]+(/[0-9]+)?).*"

But it does not work with a full date pattern (R code below):

    str = "hello 2/5/2017 123"
    gsub(".*([0-9]+/[0-9]+(/[0-9]+)?).*", "\\1", str)

Result:

    [1] "5/2017"

Any idea of what I am doing wrong ?

  • 1
    See https://regex101.com/r/6ir85T/1. Make the first `.*` lazy by replacing it with `.*?` – Wiktor Stribiżew Jul 11 '18 at 16:20
  • you could also be more restrictive for the day and month and year patterns so that they are explicit.. Also I suspect there should be a space type character before and after the date, so by using that you will make sure the .* does not capture part of the date. – Rob Jul 11 '18 at 18:47

0 Answers0