Greedy Nature

Learn about the default nature of RegEx.

Overview of greedy nature

RegExs are known for being greedy. RegEx’s greedy nature aims to match as many characters as possible before passing control to the next part of the expression.

Let’s look at an example. The text provided to you is ‘firstname’ ‘lastname’ ‘address’.

Consider the zero-based indexing for a better understanding. For the text mentioned above, a single quotation appears at index[0], a lowercase character “f” appears at index[1], a lowercase character “s” appears at index[30], and a single quote appears at index[31] and so on for the text. A single quotation appears at index[0], a wildcard character appears at index[1], and so on for the RegEx.

How greedy nature RegEx works

Let’s consider the RegEx /'.*' '.*'/. Instead of matching any pattern, let’s walk through how matching works in cases of greedy nature. After exploring all the special characters, think for a moment about what the answer will be.

When the search starts, the character ("'") at index[0] from RegEx will match the ...