Quantifier Greediness


As we've already seen, JavaScript quantifiers are "greedy" by default. That means they match the most characters they can, consistent with the regular expression they're in. For example, we tried to change the text "That is some text, isn't it?" to "That's some text, isn't it?" by replacing matches to the regular expression /.*is/ with That's . However, /.*is/ didn't match That is ; it matched That is some text, is instead, because quantifiers are greedy. That made the result of our code "That'sn't it?" , which is not what we wanted.

To fix the problem, you can make quantifiers less greedy. In fact, to match the minimum number of times possible, you follow the quantifier with a question mark ( ? ):

  • *? Match 0 or more times

  • +? Match 1 or more times

  • ?? Match 0 or 1 time

  • {n}? Match n times

  • {n,}? Match at least n times

  • {n,m}? Match at least n but not more than m times

That means that we should use the regular expression /.*?is/ in our example to match That is rather than That is some text, is . Here's what that looks like in code:

(Listing 20-13.html on the web site)
 <HTML>      <HEAD>          <TITLE>Handling Quantifier Greediness</TITLE>          <SCRIPT LANGUAGE="JavaScript">              <!--                function displayer()                 {  var regexp = /.*?is/   document.form1.text2.value = document.form1.text1.value.replace( graphics/ccc.gif regexp, "That's")  }            //-->          </SCRIPT>      </HEAD>       <BODY>          <H1>Handling Quantifier Greediness</H1>          <FORM NAME="form1">              <INPUT TYPE="TEXT" NAME="text1" VALUE="That is some text, isn't it?" graphics/ccc.gif SIZE="30">              <BR>              <INPUT TYPE="BUTTON" VALUE="Replace Text" ONCLICK="displayer()">              <BR>              <INPUT TYPE="TEXT" NAME="text2">          </FORM>      </BODY>  </HTML> 

You can see the results of this code in Figure 20.10, where we've matched just the text we want.

Figure 20.10. Making quantifiers less greedy.

graphics/20fig10.gif



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net