3

I want to extract the last occurence of a date from my source file. I use this expression to select a date:

\d{1,2}(-|\/)\d{1,2}(-|\/)\d{2,4}

How can I change it so that it only selects the last date that is encountered in the source file?

So for example, if this is the source:

19-04-2010 random text  
random text  
random text 19/5/1999  
25/12/1991 random text

I want the regex expression to return only:

25/12/1991

Can anyone help me out?

rolfheij
  • 35
  • 5
  • Maybe you can get all the dates occurences and then chose the last one. Otherwise i doubt it coulb be done easily with a regex. What language are you using? – Gwenc37 May 01 '14 at 14:07
  • Treat the entire file as a single string; then search for an occurrence that has a negative lookahead (in other words: "find x that is not followed by anything followed by x"). That will be the last occurrence. How to implement that depends on the environment in which you do this (language). – Floris May 01 '14 at 14:10

1 Answers1

3

You can use this negative lookahead to make sure only last occurrence is matched:

\d{1,2}[-\/]\d{1,2}[-\/]\d{2,4}(?![\s\S]*?\d{1,2}[-\/]\d{1,2}[-\/]\d{2,4})

Working Demo

  • This is regex implementation of approach Floris commented i.e. find x that is not followed by x"
  • I used [\s\S]*? since OP didn't specify tool/language of regex and I wasn't sure if any DOTALL equivalent flag is available.
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • 1
    You and I think alike... my comment explains your expression. Not sure I would have chosen `[\s\S]*?` for the "followed by anything" part of the expression. Can you explain? – Floris May 01 '14 at 14:11
  • I used `[\s\S]*?` since OP didn't specify tool/language of regex and I wasn't sure is any DOTALL equivalent is available. – anubhava May 01 '14 at 14:13
  • You do need to explain how this works on the entire file - in other words you need a flag (in your demo, you used `g`). – Floris May 01 '14 at 14:13
  • 1
    `g` flag is not really needed, i updated demo link. Added some explanation but more is available on the demo link. – anubhava May 01 '14 at 14:17
  • 1
    Just to clarify - does `[\s\S]*` span across multiple lines without any `DOTALL` flags? That's a good trick I didn't know. – Floris May 01 '14 at 14:23
  • 1
    Yes it does. Languages like Javascript where `DOTALL` is missing `[\s\S]*` trick is used to match text across multiple lines. – anubhava May 01 '14 at 14:25