Search code examples
regexdatenotepad++

Match first date in line with regex


I'm trying to write a regex search string for Notepad++ that will match the first date on every line.

My text looks something like this:

Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.
Nå skal folk få fred, iTromsø, 09.09.2017, Martin Lægland 31.12.2017 Publisert på nett.
Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.

I only want the first date on each line, so excluding 31.12.2017 on the second line.

I've tried \K(([0-9]{2}).([0-9]{2}).([0-9]{4})), but that only gives me the second date, not the first.


Solution

  • Code

    See regex in use here

    ^.*?\K\d+\.\d+\.\d+
    

    Results

    Input

    Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.
    Nå skal folk få fred, iTromsø, 09.09.2017, Martin Lægland 31.12.2017 Publisert på nett.
    Nå skal folk få fred, iTromsø, 09.09.2017 19:09 Martin Lægland, Publisert på nett.
    

    Output

    09.09.2017
    09.09.2017
    09.09.2017
    

    Explanation

    • ^ Assert position at the start of the line
    • .*? Match any character any number of times, but as few as possible
    • \K Reset the starting point of the reported match. Any previously consumed characters are no longer included in the final match
    • \d+\.\d+\.\d+ Match any digit one or more times, followed by a dot . literally, followed by the same thing (any digit one or more times, followed by a dot . literally), followed by any digit one or more times