Regular Expressions: Alternative Match Patterns


You also can use alternative match patterns , which enable you to specify a number of different patterns as possible matches. You can specify alternatives by using a bar () to separate them. Here's an examplethe user can type exit , or quit , or stop to match this pattern:

 function checker()  {      var regexp = /exitquitstop/      var matches = document.form1.text1.value.match(regexp)      document.form1.text2.value = "You want to quit?"  } 

Tip

Alternative match patterns are checked from left to right, and the first one that matches is used. Note, therefore, that a pattern that could match may not be used if an earlier pattern has already matched (which is important to know if, for example, the later, unused, pattern uses parentheses to return various substrings and the earlier, matching, pattern doesn't).


To make it more clear that a number of patterns make up various alternatives, it's customary to put them in parentheses so that they don't interfere with the rest of the regular expression. When you're specifying alternate match patterns using the character, enclosing parentheses are treated just as enclosing alternative match patterns, not creating submatches (as parentheses normally do in a match pattern):

 function checker()  {  var regexp = /(exitquitstop)/  var matches = document.form1.text1.value.match(regexp)      document.form1.text2.value = "You want to quit?"  } 

Now we can understand more of this match pattern that we saw earlier in this chapter (Listing 20-03.html) to match datesthe parentheses around 18 19 20 are really just to group alternative match patterns so that we can match years starting with 18, 19, or 20:

 var regexp = /^(0?[1-9]1[0-2])\/(0?[1-9][12][0-9]3[01])\/((181920)\d{2})$/ 

Tip

Note that you can use to specify alternative matches inside parentheses, but not inside square brackets, which create character classes. The character class [18 19 20] is the same as [01289 ] , for example, because all characters in it are treated as literal, not special, characters .




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