norr
norr

Reputation: 2177

Regular expression - find from start to end but only first match

I need to find two words in text, and replace text between. So I have this regular expression:

(START[a-zA-Z\s]+STOP)

and this text:

banana car START house apple computer STOP mouse money

(bold text is matched).

But when I have multiple STOP words, then this match to the last one, because STOP is also [a-zA-Z\s] pattern.

banana car START house apple computer STOP mouse money STOP orange

How I can change this regular expression to stop matching at first appearance of word? This is what I need to get:

banana car START house apple computer STOP mouse money STOP orange

Upvotes: 1

Views: 143

Answers (1)

Shafizadeh
Shafizadeh

Reputation: 10360

By adding a ? after +. So use this pattern:

/(START[a-zA-Z\s]+?STOP)/

Online Demo

Your pattern (without ?) matches first STOP as [a-zA-Z\s]+.

Upvotes: 2

Related Questions