Regex match for first ending

Question:

I have a text like this sample. i want to match first "something" in my text. the "something" have any character in it, so i should use (.*) for it.

Sample:
start: something, end ... blah blah ... start: something, end

I tried to match it like this:
start: (.*) end

but as you can expect this see last end in my text.

https://www.debuggex.com/r/qfeBXsBybijWDWbp

Asked By: Purya

||

Answers:

You just need to add a ? to your current regex:

start: (.*?) end

https://www.debuggex.com/r/1VmZTRx0EqgNyH4Y

This will tell the .* to match lazily until the word "end".

Answered By: M B

Use a non-greedy match: start: (.*?) end.

Keep in mind it won’t match well if something has end inside it.

Answered By: Bharel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.