1

I am trying to alter the reg. expression below to take into account an extra space between the month and the day as follows:

(?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s\d{1,2}\s\d{1,2}:\d{1,2}

rats 1.4K Sep  9 08:10 /opt/rats/prod ===> it returns blank
rats 1.4K Sep 12 08:10 /opt/rats/prod ===> returns "Sep 12 08:10"

If I add \s it works in the first string but it breaks on the second string:

(?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s\s\d{1,2}\s\d{1,2}:\d{1,2}

Thank you

Max
  • 1,289
  • 3
  • 26
  • 50
  • 2
    Match for 1 or 2 spaces the same way you're matching for 1 or 2 digits, with `\s{1,2}`. – Jonathon Chase Sep 20 '18 at 21:23
  • 1
    Why arent you just parsing using `DateTime.TryParse()`? You obviously have some text before the date, but it looks like it is a constant, so just remove it before parsing – maccettura Sep 20 '18 at 21:31
  • @maccettura: parsing depends on the culture of the user so TryParse cannot provide me that plus if it fails I dont get an exception, it will return me a 1/1 bogus date. – Max Sep 20 '18 at 21:55
  • @Max `TryParse()` returns a bool, so you know if it fails. Also, wouldnt your regex be culture dependent since its in English? You can always [use `InvarianatCulture`](https://stackoverflow.com/questions/46778141/datetime-formats-used-in-invariantculture) too.. – maccettura Sep 20 '18 at 21:57

2 Answers2

1

To match exactly extra space

(?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s{1,2}\d{1,2}\s\d{1,2}:\d{1,2}

To match any count of extra spaces

(?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s+\d{1,2}\s\d{1,2}:\d{1,2}
Ahmed Yousif
  • 2,298
  • 1
  • 11
  • 17
  • @Max Is the text before and after the date always the same? If it is not the same text, is the order still the same (e.g The date is always the 2nd, 3rd and 4th index) – maccettura Sep 20 '18 at 21:41
0

You can try this: \s{1}\d{2} or \s{2}\d{1}

(?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))(\s{1}\d{2}|\s{2}\d{1})\s\d{1,2}:\d{1,2}
Hossein Golshani
  • 1,847
  • 5
  • 16
  • 27