Defining nongreedy quantifiers

In the previous section, we had a look at multipliers, where you can specify that a pattern should be repeated a certain number of times. By default, JavaScript will try and match the largest number of characters possible, which means that it will be a greedy match. Let's say we have a pattern similar to /d{1,4}/ that will match any text and has between one and four numbers. By default, if we use 124582948, it will return 1245, as it will take the maximum number of options (greedy approach). However, if we want, we can add the (?) question mark operator to tell JavaScript not to use greedy matching and instead return the minimum number of characters as possible:

Defining nongreedy quantifiers

Greedy matching is something that makes it difficult to find bugs in your code. Consider the following example text:

<div class="container" id="main">
   Site content  
<div>

If we wanted to extract the class, you might think of writing a pattern in this way:

/class=".*"/

The problem here is that the * character will attempt to match as many characters as possible, so instead of getting container like we wanted, we would get "container" id="main". Since the dot character will match anything, the regular expression will match from the first quotation mark before the class word to the closing quotation mark right before the id word. To fix this, we can use the ungreedy question mark and change the pattern to /class=".*?"/. This will cause it to stop at the minimum required match, which is when we reach the first quotation mark:

Defining nongreedy quantifiers
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset