RegEx - stop after first match

schojo picture schojo · Jul 15, 2016 · Viewed 13.5k times · Source

we're using this regex to filter a ticket number from the subject.

This is the regex we're using: \\[\\#(.*)\\]

The subject usually looks like this: "[#20160708-0020] Hello blah blah"

Regex get's us "20160708-0020" and we can use that further.

Somebody from the company started writing mails like this: "[#20160708-0020] Hello [SQL] blah blah"

So the regex will get us "20160708-0020] Hello [SQL" which obviously isn't correct.

Is there any way to tell the regex to stop after the first match? Thanks! :)

Answer

Bryce Drew picture Bryce Drew · Jul 15, 2016

https://regex101.com/r/sY4pG6/1

\[\#(.*?)\]

The * in your regex is greedy. It will capture as much as possible.

The *? above is lazy. It will capture as little as possible. This will make your regex stop after that first match.