Regexp non greedy and greedy pattern

Deepak Kumar
1 min readSep 19, 2016

--

Lets get into the matter right away, take the regular expression below as an example. It will try to match any character at least once.

/.+/

The above pattern is greedy because it tries to match till the end of the input. It won’t stop at the first match. For example suppose we have some html content as shown below.

<h>title</h><p>Content goes here …</p>

Say we are parsing the above text with the patten to extract the tags with the regular expression /<.+>/. We get the entire sentence as match because the matching doesn’t end at the first </h>, it continues till the end and matches with the last </p>.

So how do we make it non-greedy ?

.+?

By adding “?” the pattern becomes non greedy ie. the matching ends when the first time match happens. Now if you try to match the above example with non greedy patters /<.+?>/. The matching will happen at each tag enclosed in <>.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Deepak Kumar
Deepak Kumar

No responses yet

Write a response