Search

6/03/2010

javascritp regular expression


var re = /\d?/; // 0 or 1
re = /\d+/; // 1 or more
re = /\d*/; // 0 or more
re = /\d{3}/; // Exactly 3 times
re = /\d{3,}/; // 3 or more times
re = /\d{3,5}/; // At least 3, but not more than 5 times



‘aaa’.match(/a+/) // [‘aaa’]
‘aaa’.match(/a+?/) // [‘a’]

11.1.3.1. Nongreedy repetition
The repetition characters listed in Table 11-3 match as many times as possible while still allowing any following parts of the regular expression to match. We say that this repetition is "greedy." It is also possible (in JavaScript 1.5 and later; this is one of the Perl 5 features not implemented in JavaScript 1.2) to specify that repetition should be done in a nongreedy way. Simply follow the repetition character or characters with a question mark: ??, +?, *?, or even {1,5}?. For example, the regular expression /a+/ matches one or more occurrences of the letter a. When applied to the string "aaa", it matches all three letters. But /a+?/ matches one or more occurrences of the letter a, matching as few characters as necessary. When applied to the same string, this pattern matches only the first letter a.

Using nongreedy repetition may not always produce the results you expect. Consider the pattern /a*b/, which matches zero or more letter a's, followed by the letter b. When applied to the string "aaab", it matches the entire string. Now let's use the nongreedy version: /a*?b/. This should match the letter b preceded by the fewest number of a's possible. When applied to the same string "aaab", you might expect it to match only the last letter b. In fact, however, this pattern matches the entire string as well, just like the greedy version of the pattern. This is because regular-expression pattern matching is done by finding the first position in the string at which a match is possible. The nongreedy version of our pattern does match at the first character of the string, so this match is returned; matches at subsequent characters are never even considered.

沒有留言: