| 1 | <html><head><meta name="robots" content="index,follow"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"> |
| 2 | <title>Regular expressions 2. Quantifiers</title> |
| 3 | <style> |
| 4 | td { padding-left: 5pt; padding-right: 5pt; } |
| 5 | th { padding-left: 5pt; padding-right: 5pt; } |
| 6 | code { white-space: pre-wrap; } |
| 7 | dd { white-space: pre-wrap; } |
| 8 | </style> |
| 9 | </head><body bgcolor="#FFFFFF"> |
| 10 | |
| 11 | <table border=0 cellpadding=0 cellspacing=0><tr><td bgcolor="#CCCC00"><table border=4 cellpadding=9><tr><td align=middle bgcolor="#000000"><font face="Palatino,Times" size=6 color="#999900"><b> |
| 12 | Regular expressions 2. Quantifiers |
| 13 | </b></font></table></table> |
| 14 | <p>Quantifiers specify how often the preceding <a href="Regular_expressions.html">regular expression</a> should match.</p> |
| 15 | <dl> |
| 16 | <dt><b>*</b> Try to match the preceding regular expression zero or more times. |
| 17 | <dd> Example: "(ab)c*" matches "ab" followed by zero or more "c"s, i.e., "ab", "abc", "abcc", "abccc" ...</dd> |
| 18 | <dt><b>+</b> Try to match the preceding regular expression one or more times. |
| 19 | <dd> Example: "(ab)c+" matches "ab" followed by one or more "c"s, i.e., "abc", "abcc", "abccc" ...</dd> |
| 20 | <dt><b>{<i>m</i>, <i>n</i>}</b> Try to match the preceding regular expression between <i>m</i> and <i>n</i> times. |
| 21 | <dd>If you leave <i>m</i> out, it is assumed to be zero. If you leave <i>n</i> out it is assumed to be infinity. I.e., "{,<i>n</i>}" matches from <i>zero</i> to <i>n</i> times, "{<i>m</i>,}" matches a minimum of <i>m</i> times, "{,}" matches the same as "*" and "{n}" is shorthand for "{n, n"} and matches exactly <i>n</i> times.</dd> |
| 22 | <dd> Example: "(ab){1,2}" matches "ab" and "abab".</dd> |
| 23 | <dt><b>?</b> Try to match zero or one time. |
| 24 | </dl> |
| 25 | <h2>Changing match behaviour</h2> |
| 26 | <p>Default the quantifiers above try to match as much as possible, they are <i>greedy</i>. You can change greedy behaviour to <i>lazy</i> behaviour by adding an extra "?" after the quantifier.</p> |
| 27 | <dl> |
| 28 | <dd> Example: In the string "cabddde", the search "abd{1,2}" matches "abdd", while the search for "abd{1,2}?" matches "abd".</dd> |
| 29 | <dd> Example: In the string "cabddde", the search "abd+" matches "abddd", while the search for "abd+?" matches "abd".</dd> |
| 30 | </dl> |
| 31 | <h3>Links to this page</h3> |
| 32 | <ul> |
| 33 | <li><a href="Regular_expressions_1__Special_characters.html">Regular expressions 1. Special characters</a> |
| 34 | </ul> |
| 35 | <hr> |
| 36 | <address> |
| 37 | <p>© djmw 20010708</p> |
| 38 | </address> |
| 39 | </body> |
| 40 | </html> |