Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx - stop after first match [duplicate]

Tags:

regex

otrs

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! :)

like image 832
schojo Avatar asked Jan 06 '23 17:01

schojo


2 Answers

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.

like image 158
Bryce Drew Avatar answered Jan 19 '23 01:01

Bryce Drew


In order to stop it before it goes further, you'll want to make your expression lazy.

\[\#(.*?)\]

Notice the question mark after the asterisk.

like image 31
Swivel Avatar answered Jan 19 '23 00:01

Swivel