Search code examples
regexquantifiersnon-greedyspiceworks

Regex searching for time doesn't want to be non-greedy


I'm trying to run a regex in Spiceworks to parse through email headers to select the first instance of time for ticket assignment purposes. The regex itself works, but it picks up all instances of time rather than just one.

Here's the regex: \.*(0[1]|1[3-7]):\d\d:\d\d

I've tried to make in non-greedy by doing this: \.*?(0[1]|1[3-7]):\d\d:\d\d but that doesn't seem to work. Putting the question mark in front of a quantifier didn't do anything for this purpose.

What is a good solution to make this regex non-greedy or pick up only the first instance?

Thanks,

Andrew N.

Edit: What I'm trying to achieve from the regex is something like "13:04:57" instead of the whole date.

Sample string: Received: by 127.0.0.1 with SMTP id co5csp22954317qdb; Wed, 6 May 2015 13:02:22 -0700 (PDT) X-Received: by 127.0.0.1 with SMTP id j185mr26699743oig.68.1430928141923; Wed, 06 May 2015 13:02:21 -0700 (PDT)


Solution

  • You can use this lookahead based regex to match first instance of the time matched by your regex:

    /^(?:(?!(?:0[1]|1[3-7]):\d\d:\d\d).)*((?:0[1]|1[3-7]):\d\d:\d\d)/m
    

    (?!...) is a negative lookahead that makes sure there is no other instance of time before matching a time thus matching only first instance.

    RegEx Demo