1. /*
  2. * @(#)Pattern.java 1.97 04/01/13
  3. *
  4. * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
  5. * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
  6. */
  7. package java.util.regex;
  8. import java.security.AccessController;
  9. import java.security.PrivilegedAction;
  10. import java.text.CharacterIterator;
  11. import sun.text.Normalizer;
  12. import java.util.ArrayList;
  13. import java.util.HashMap;
  14. /**
  15. * A compiled representation of a regular expression.
  16. *
  17. * <p> A regular expression, specified as a string, must first be compiled into
  18. * an instance of this class. The resulting pattern can then be used to create
  19. * a {@link Matcher} object that can match arbitrary {@link
  20. * java.lang.CharSequence </code>character sequences<code>} against the regular
  21. * expression. All of the state involved in performing a match resides in the
  22. * matcher, so many matchers can share the same pattern.
  23. *
  24. * <p> A typical invocation sequence is thus
  25. *
  26. * <blockquote><pre>
  27. * Pattern p = Pattern.{@link #compile compile}("a*b");
  28. * Matcher m = p.{@link #matcher matcher}("aaaaab");
  29. * boolean b = m.{@link Matcher#matches matches}();</pre></blockquote>
  30. *
  31. * <p> A {@link #matches matches} method is defined by this class as a
  32. * convenience for when a regular expression is used just once. This method
  33. * compiles an expression and matches an input sequence against it in a single
  34. * invocation. The statement
  35. *
  36. * <blockquote><pre>
  37. * boolean b = Pattern.matches("a*b", "aaaaab");</pre></blockquote>
  38. *
  39. * is equivalent to the three statements above, though for repeated matches it
  40. * is less efficient since it does not allow the compiled pattern to be reused.
  41. *
  42. * <p> Instances of this class are immutable and are safe for use by multiple
  43. * concurrent threads. Instances of the {@link Matcher} class are not safe for
  44. * such use.
  45. *
  46. *
  47. * <a name="sum">
  48. * <h4> Summary of regular-expression constructs </h4>
  49. *
  50. * <table border="0" cellpadding="1" cellspacing="0"
  51. * summary="Regular expression constructs, and what they match">
  52. *
  53. * <tr align="left">
  54. * <th bgcolor="#CCCCFF" align="left" id="construct">Construct</th>
  55. * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th>
  56. * </tr>
  57. *
  58. * <tr><th> </th></tr>
  59. * <tr align="left"><th colspan="2" id="characters">Characters</th></tr>
  60. *
  61. * <tr><td valign="top" headers="construct characters"><i>x</i></td>
  62. * <td headers="matches">The character <i>x</i></td></tr>
  63. * <tr><td valign="top" headers="construct characters"><tt>\\</tt></td>
  64. * <td headers="matches">The backslash character</td></tr>
  65. * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>n</i></td>
  66. * <td headers="matches">The character with octal value <tt>0</tt><i>n</i>
  67. * (0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
  68. * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>nn</i></td>
  69. * <td headers="matches">The character with octal value <tt>0</tt><i>nn</i>
  70. * (0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
  71. * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>mnn</i></td>
  72. * <td headers="matches">The character with octal value <tt>0</tt><i>mnn</i>
  73. * (0 <tt><=</tt> <i>m</i> <tt><=</tt> 3,
  74. * 0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
  75. * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>hh</i></td>
  76. * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>hh</i></td></tr>
  77. * <tr><td valign="top" headers="construct characters"><tt>\u</tt><i>hhhh</i></td>
  78. * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>hhhh</i></td></tr>
  79. * <tr><td valign="top" headers="matches"><tt>\t</tt></td>
  80. * <td headers="matches">The tab character (<tt>'\u0009'</tt>)</td></tr>
  81. * <tr><td valign="top" headers="construct characters"><tt>\n</tt></td>
  82. * <td headers="matches">The newline (line feed) character (<tt>'\u000A'</tt>)</td></tr>
  83. * <tr><td valign="top" headers="construct characters"><tt>\r</tt></td>
  84. * <td headers="matches">The carriage-return character (<tt>'\u000D'</tt>)</td></tr>
  85. * <tr><td valign="top" headers="construct characters"><tt>\f</tt></td>
  86. * <td headers="matches">The form-feed character (<tt>'\u000C'</tt>)</td></tr>
  87. * <tr><td valign="top" headers="construct characters"><tt>\a</tt></td>
  88. * <td headers="matches">The alert (bell) character (<tt>'\u0007'</tt>)</td></tr>
  89. * <tr><td valign="top" headers="construct characters"><tt>\e</tt></td>
  90. * <td headers="matches">The escape character (<tt>'\u001B'</tt>)</td></tr>
  91. * <tr><td valign="top" headers="construct characters"><tt>\c</tt><i>x</i></td>
  92. * <td headers="matches">The control character corresponding to <i>x</i></td></tr>
  93. *
  94. * <tr><th> </th></tr>
  95. * <tr align="left"><th colspan="2" id="classes">Character classes</th></tr>
  96. *
  97. * <tr><td valign="top" headers="construct classes"><tt>[abc]</tt></td>
  98. * <td headers="matches"><tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (simple class)</td></tr>
  99. * <tr><td valign="top" headers="construct classes"><tt>[^abc]</tt></td>
  100. * <td headers="matches">Any character except <tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (negation)</td></tr>
  101. * <tr><td valign="top" headers="construct classes"><tt>[a-zA-Z]</tt></td>
  102. * <td headers="matches"><tt>a</tt> through <tt>z</tt>
  103. * or <tt>A</tt> through <tt>Z</tt>, inclusive (range)</td></tr>
  104. * <tr><td valign="top" headers="construct classes"><tt>[a-d[m-p]]</tt></td>
  105. * <td headers="matches"><tt>a</tt> through <tt>d</tt>,
  106. * or <tt>m</tt> through <tt>p</tt>: <tt>[a-dm-p]</tt> (union)</td></tr>
  107. * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[def]]</tt></td>
  108. * <td headers="matches"><tt>d</tt>, <tt>e</tt>, or <tt>f</tt> (intersection)</tr>
  109. * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^bc]]</tt></td>
  110. * <td headers="matches"><tt>a</tt> through <tt>z</tt>,
  111. * except for <tt>b</tt> and <tt>c</tt>: <tt>[ad-z]</tt> (subtraction)</td></tr>
  112. * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^m-p]]</tt></td>
  113. * <td headers="matches"><tt>a</tt> through <tt>z</tt>,
  114. * and not <tt>m</tt> through <tt>p</tt>: <tt>[a-lq-z]</tt>(subtraction)</td></tr>
  115. * <tr><th> </th></tr>
  116. *
  117. * <tr align="left"><th colspan="2" id="predef">Predefined character classes</th></tr>
  118. *
  119. * <tr><td valign="top" headers="construct predef"><tt>.</tt></td>
  120. * <td headers="matches">Any character (may or may not match <a href="#lt">line terminators</a>)</td></tr>
  121. * <tr><td valign="top" headers="construct predef"><tt>\d</tt></td>
  122. * <td headers="matches">A digit: <tt>[0-9]</tt></td></tr>
  123. * <tr><td valign="top" headers="construct predef"><tt>\D</tt></td>
  124. * <td headers="matches">A non-digit: <tt>[^0-9]</tt></td></tr>
  125. * <tr><td valign="top" headers="construct predef"><tt>\s</tt></td>
  126. * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
  127. * <tr><td valign="top" headers="construct predef"><tt>\S</tt></td>
  128. * <td headers="matches">A non-whitespace character: <tt>[^\s]</tt></td></tr>
  129. * <tr><td valign="top" headers="construct predef"><tt>\w</tt></td>
  130. * <td headers="matches">A word character: <tt>[a-zA-Z_0-9]</tt></td></tr>
  131. * <tr><td valign="top" headers="construct predef"><tt>\W</tt></td>
  132. * <td headers="matches">A non-word character: <tt>[^\w]</tt></td></tr>
  133. *
  134. * <tr><th> </th></tr>
  135. * <tr align="left"><th colspan="2" id="posix">POSIX character classes</b> (US-ASCII only)<b></th></tr>
  136. *
  137. * <tr><td valign="top" headers="construct posix"><tt>\p{Lower}</tt></td>
  138. * <td headers="matches">A lower-case alphabetic character: <tt>[a-z]</tt></td></tr>
  139. * <tr><td valign="top" headers="construct posix"><tt>\p{Upper}</tt></td>
  140. * <td headers="matches">An upper-case alphabetic character:<tt>[A-Z]</tt></td></tr>
  141. * <tr><td valign="top" headers="construct posix"><tt>\p{ASCII}</tt></td>
  142. * <td headers="matches">All ASCII:<tt>[\x00-\x7F]</tt></td></tr>
  143. * <tr><td valign="top" headers="construct posix"><tt>\p{Alpha}</tt></td>
  144. * <td headers="matches">An alphabetic character:<tt>[\p{Lower}\p{Upper}]</tt></td></tr>
  145. * <tr><td valign="top" headers="construct posix"><tt>\p{Digit}</tt></td>
  146. * <td headers="matches">A decimal digit: <tt>[0-9]</tt></td></tr>
  147. * <tr><td valign="top" headers="construct posix"><tt>\p{Alnum}</tt></td>
  148. * <td headers="matches">An alphanumeric character:<tt>[\p{Alpha}\p{Digit}]</tt></td></tr>
  149. * <tr><td valign="top" headers="construct posix"><tt>\p{Punct}</tt></td>
  150. * <td headers="matches">Punctuation: One of <tt>!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~</tt></td></tr>
  151. * <!-- <tt>[\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]</tt>
  152. * <tt>[\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]</tt> -->
  153. * <tr><td valign="top" headers="construct posix"><tt>\p{Graph}</tt></td>
  154. * <td headers="matches">A visible character: <tt>[\p{Alnum}\p{Punct}]</tt></td></tr>
  155. * <tr><td valign="top" headers="construct posix"><tt>\p{Print}</tt></td>
  156. * <td headers="matches">A printable character: <tt>[\p{Graph}]</tt></td></tr>
  157. * <tr><td valign="top" headers="construct posix"><tt>\p{Blank}</tt></td>
  158. * <td headers="matches">A space or a tab: <tt>[ \t]</tt></td></tr>
  159. * <tr><td valign="top" headers="construct posix"><tt>\p{Cntrl}</tt></td>
  160. * <td headers="matches">A control character: <tt>[\x00-\x1F\x7F]</td></tr>
  161. * <tr><td valign="top" headers="construct posix"><tt>\p{XDigit}</tt></td>
  162. * <td headers="matches">A hexadecimal digit: <tt>[0-9a-fA-F]</tt></td></tr>
  163. * <tr><td valign="top" headers="construct posix"><tt>\p{Space}</tt></td>
  164. * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
  165. *
  166. * <tr><th> </th></tr>
  167. * <tr align="left"><th colspan="2" id="unicode">Classes for Unicode blocks and categories</th></tr>
  168. *
  169. * <tr><td valign="top" headers="construct unicode"><tt>\p{InGreek}</tt></td>
  170. * <td headers="matches">A character in the Greek block (simple <a href="#ubc">block</a>)</td></tr>
  171. * <tr><td valign="top" headers="construct unicode"><tt>\p{Lu}</tt></td>
  172. * <td headers="matches">An uppercase letter (simple <a href="#ubc">category</a>)</td></tr>
  173. * <tr><td valign="top" headers="construct unicode"><tt>\p{Sc}</tt></td>
  174. * <td headers="matches">A currency symbol</td></tr>
  175. * <tr><td valign="top" headers="construct unicode"><tt>\P{InGreek}</tt></td>
  176. * <td headers="matches">Any character except one in the Greek block (negation)</td></tr>
  177. * <tr><td valign="top" headers="construct unicode"><tt>[\p{L}&&[^\p{Lu}]] </tt></td>
  178. * <td headers="matches">Any letter except an uppercase letter (subtraction)</td></tr>
  179. *
  180. * <tr><th> </th></tr>
  181. * <tr align="left"><th colspan="2" id="bounds">Boundary matchers</th></tr>
  182. *
  183. * <tr><td valign="top" headers="construct bounds"><tt>^</tt></td>
  184. * <td headers="matches">The beginning of a line</td></tr>
  185. * <tr><td valign="top" headers="construct bounds"><tt>$</tt></td>
  186. * <td headers="matches">The end of a line</td></tr>
  187. * <tr><td valign="top" headers="construct bounds"><tt>\b</tt></td>
  188. * <td headers="matches">A word boundary</td></tr>
  189. * <tr><td valign="top" headers="construct bounds"><tt>\B</tt></td>
  190. * <td headers="matches">A non-word boundary</td></tr>
  191. * <tr><td valign="top" headers="construct bounds"><tt>\A</tt></td>
  192. * <td headers="matches">The beginning of the input</td></tr>
  193. * <tr><td valign="top" headers="construct bounds"><tt>\G</tt></td>
  194. * <td headers="matches">The end of the previous match</td></tr>
  195. * <tr><td valign="top" headers="construct bounds"><tt>\Z</tt></td>
  196. * <td headers="matches">The end of the input but for the final
  197. * <a href="#lt">terminator</a>, if any</td></tr>
  198. * <tr><td valign="top" headers="construct bounds"><tt>\z</tt></td>
  199. * <td headers="matches">The end of the input</td></tr>
  200. *
  201. * <tr><th> </th></tr>
  202. * <tr align="left"><th colspan="2" id="greedy">Greedy quantifiers</th></tr>
  203. *
  204. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>?</tt></td>
  205. * <td headers="matches"><i>X</i>, once or not at all</td></tr>
  206. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>*</tt></td>
  207. * <td headers="matches"><i>X</i>, zero or more times</td></tr>
  208. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>+</tt></td>
  209. * <td headers="matches"><i>X</i>, one or more times</td></tr>
  210. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>}</tt></td>
  211. * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
  212. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,}</tt></td>
  213. * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
  214. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}</tt></td>
  215. * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
  216. *
  217. * <tr><th> </th></tr>
  218. * <tr align="left"><th colspan="2" id="reluc">Reluctant quantifiers</th></tr>
  219. *
  220. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>??</tt></td>
  221. * <td headers="matches"><i>X</i>, once or not at all</td></tr>
  222. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>*?</tt></td>
  223. * <td headers="matches"><i>X</i>, zero or more times</td></tr>
  224. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>+?</tt></td>
  225. * <td headers="matches"><i>X</i>, one or more times</td></tr>
  226. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>}?</tt></td>
  227. * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
  228. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,}?</tt></td>
  229. * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
  230. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}?</tt></td>
  231. * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
  232. *
  233. * <tr><th> </th></tr>
  234. * <tr align="left"><th colspan="2" id="poss">Possessive quantifiers</th></tr>
  235. *
  236. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>?+</tt></td>
  237. * <td headers="matches"><i>X</i>, once or not at all</td></tr>
  238. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>*+</tt></td>
  239. * <td headers="matches"><i>X</i>, zero or more times</td></tr>
  240. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>++</tt></td>
  241. * <td headers="matches"><i>X</i>, one or more times</td></tr>
  242. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>}+</tt></td>
  243. * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
  244. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,}+</tt></td>
  245. * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
  246. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}+</tt></td>
  247. * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
  248. *
  249. * <tr><th> </th></tr>
  250. * <tr align="left"><th colspan="2" id="logical">Logical operators</th></tr>
  251. *
  252. * <tr><td valign="top" headers="construct logical"><i>XY</i></td>
  253. * <td headers="matches"><i>X</i> followed by <i>Y</i></td></tr>
  254. * <tr><td valign="top" headers="construct logical"><i>X</i><tt>|</tt><i>Y</i></td>
  255. * <td headers="matches">Either <i>X</i> or <i>Y</i></td></tr>
  256. * <tr><td valign="top" headers="construct logical"><tt>(</tt><i>X</i><tt>)</tt></td>
  257. * <td headers="matches">X, as a <a href="#cg">capturing group</a></td></tr>
  258. *
  259. * <tr><th> </th></tr>
  260. * <tr align="left"><th colspan="2" id="backref">Back references</th></tr>
  261. *
  262. * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>n</i></td>
  263. * <td valign="bottom" headers="matches">Whatever the <i>n</i><sup>th</sup>
  264. * <a href="#cg">capturing group</a> matched</td></tr>
  265. *
  266. * <tr><th> </th></tr>
  267. * <tr align="left"><th colspan="2" id="quot">Quotation</th></tr>
  268. *
  269. * <tr><td valign="top" headers="construct quot"><tt>\</tt></td>
  270. * <td headers="matches">Nothing, but quotes the following character</tt></td></tr>
  271. * <tr><td valign="top" headers="construct quot"><tt>\Q</tt></td>
  272. * <td headers="matches">Nothing, but quotes all characters until <tt>\E</tt></td></tr>
  273. * <tr><td valign="top" headers="construct quot"><tt>\E</tt></td>
  274. * <td headers="matches">Nothing, but ends quoting started by <tt>\Q</tt></td></tr>
  275. * <!-- Metachars: !$()*+.<>?[\]^{|} -->
  276. *
  277. * <tr><th> </th></tr>
  278. * <tr align="left"><th colspan="2" id="special">Special constructs (non-capturing)</th></tr>
  279. *
  280. * <tr><td valign="top" headers="construct special"><tt>(?:</tt><i>X</i><tt>)</tt></td>
  281. * <td headers="matches"><i>X</i>, as a non-capturing group</td></tr>
  282. * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux) </tt></td>
  283. * <td headers="matches">Nothing, but turns match flags on - off</td></tr>
  284. * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux:</tt><i>X</i><tt>)</tt>  </td>
  285. * <td headers="matches"><i>X</i>, as a <a href="#cg">non-capturing group</a> with the
  286. * given flags on - off</td></tr>
  287. * <tr><td valign="top" headers="construct special"><tt>(?=</tt><i>X</i><tt>)</tt></td>
  288. * <td headers="matches"><i>X</i>, via zero-width positive lookahead</td></tr>
  289. * <tr><td valign="top" headers="construct special"><tt>(?!</tt><i>X</i><tt>)</tt></td>
  290. * <td headers="matches"><i>X</i>, via zero-width negative lookahead</td></tr>
  291. * <tr><td valign="top" headers="construct special"><tt>(?<=</tt><i>X</i><tt>)</tt></td>
  292. * <td headers="matches"><i>X</i>, via zero-width positive lookbehind</td></tr>
  293. * <tr><td valign="top" headers="construct special"><tt>(?<!</tt><i>X</i><tt>)</tt></td>
  294. * <td headers="matches"><i>X</i>, via zero-width negative lookbehind</td></tr>
  295. * <tr><td valign="top" headers="construct special"><tt>(?></tt><i>X</i><tt>)</tt></td>
  296. * <td headers="matches"><i>X</i>, as an independent, non-capturing group</td></tr>
  297. *
  298. * </table>
  299. *
  300. * <hr>
  301. *
  302. *
  303. * <a name="bs">
  304. * <h4> Backslashes, escapes, and quoting </h4>
  305. *
  306. * <p> The backslash character (<tt>'\'</tt>) serves to introduce escaped
  307. * constructs, as defined in the table above, as well as to quote characters
  308. * that otherwise would be interpreted as unescaped constructs. Thus the
  309. * expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a
  310. * left brace.
  311. *
  312. * <p> It is an error to use a backslash prior to any alphabetic character that
  313. * does not denote an escaped construct; these are reserved for future
  314. * extensions to the regular-expression language. A backslash may be used
  315. * prior to a non-alphabetic character regardless of whether that character is
  316. * part of an unescaped construct.
  317. *
  318. * <p> Backslashes within string literals in Java source code are interpreted
  319. * as required by the <a
  320. * href="http://java.sun.com/docs/books/jls/second_edition/html/">Java Language
  321. * Specification</a> as either <a
  322. * href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#100850">Unicode
  323. * escapes</a> or other <a
  324. * href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#101089">character
  325. * escapes</a>. It is therefore necessary to double backslashes in string
  326. * literals that represent regular expressions to protect them from
  327. * interpretation by the Java bytecode compiler. The string literal
  328. * <tt>"\b"</tt>, for example, matches a single backspace character when
  329. * interpreted as a regular expression, while <tt>"\\b"</tt> matches a
  330. * word boundary. The string literal <tt>"\(hello\)"</tt> is illegal
  331. * and leads to a compile-time error; in order to match the string
  332. * <tt>(hello)</tt> the string literal <tt>"\\(hello\\)"</tt>
  333. * must be used.
  334. *
  335. * <a name="cc">
  336. * <h4> Character Classes </h4>
  337. *
  338. * <p> Character classes may appear within other character classes, and
  339. * may be composed by the union operator (implicit) and the intersection
  340. * operator (<tt>&&</tt>).
  341. * The union operator denotes a class that contains every character that is
  342. * in at least one of its operand classes. The intersection operator
  343. * denotes a class that contains every character that is in both of its
  344. * operand classes.
  345. *
  346. * <p> The precedence of character-class operators is as follows, from
  347. * highest to lowest:
  348. *
  349. * <blockquote><table border="0" cellpadding="1" cellspacing="0"
  350. * summary="Precedence of character class operators.">
  351. * <tr><th>1    </th>
  352. * <td>Literal escape    </td>
  353. * <td><tt>\x</tt></td></tr>
  354. * <tr><th>2    </th>
  355. * <td>Grouping</td>
  356. * <td><tt>[...]</tt></td></tr>
  357. * <tr><th>3    </th>
  358. * <td>Range</td>
  359. * <td><tt>a-z</tt></td></tr>
  360. * <tr><th>4    </th>
  361. * <td>Union</td>
  362. * <td><tt>[a-e][i-u]<tt></td></tr>
  363. * <tr><th>5    </th>
  364. * <td>Intersection</td>
  365. * <td><tt>[a-z&&[aeiou]]</tt></td></tr>
  366. * </table></blockquote>
  367. *
  368. * <p> Note that a different set of metacharacters are in effect inside
  369. * a character class than outside a character class. For instance, the
  370. * regular expression <tt>.</tt> loses its special meaning inside a
  371. * character class, while the expression <tt>-</tt> becomes a range
  372. * forming metacharacter.
  373. *
  374. * <a name="lt">
  375. * <h4> Line terminators </h4>
  376. *
  377. * <p> A <i>line terminator</i> is a one- or two-character sequence that marks
  378. * the end of a line of the input character sequence. The following are
  379. * recognized as line terminators:
  380. *
  381. * <ul>
  382. *
  383. * <li> A newline (line feed) character (<tt>'\n'</tt>),
  384. *
  385. * <li> A carriage-return character followed immediately by a newline
  386. * character (<tt>"\r\n"</tt>),
  387. *
  388. * <li> A standalone carriage-return character (<tt>'\r'</tt>),
  389. *
  390. * <li> A next-line character (<tt>'\u0085'</tt>),
  391. *
  392. * <li> A line-separator character (<tt>'\u2028'</tt>), or
  393. *
  394. * <li> A paragraph-separator character (<tt>'\u2029</tt>).
  395. *
  396. * </ul>
  397. * <p>If {@link #UNIX_LINES} mode is activated, then the only line terminators
  398. * recognized are newline characters.
  399. *
  400. * <p> The regular expression <tt>.</tt> matches any character except a line
  401. * terminator unless the {@link #DOTALL} flag is specified.
  402. *
  403. * <p> By default, the regular expressions <tt>^</tt> and <tt>$</tt> ignore
  404. * line terminators and only match at the beginning and the end, respectively,
  405. * of the entire input sequence. If {@link #MULTILINE} mode is activated then
  406. * <tt>^</tt> matches at the beginning of input and after any line terminator
  407. * except at the end of input. When in {@link #MULTILINE} mode <tt>$</tt>
  408. * matches just before a line terminator or the end of the input sequence.
  409. *
  410. * <a name="cg">
  411. * <h4> Groups and capturing </h4>
  412. *
  413. * <p> Capturing groups are numbered by counting their opening parentheses from
  414. * left to right. In the expression <tt>((A)(B(C)))</tt>, for example, there
  415. * are four such groups: </p>
  416. *
  417. * <blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings">
  418. * <tr><th>1    </th>
  419. * <td><tt>((A)(B(C)))</tt></td></tr>
  420. * <tr><th>2    </th>
  421. * <td><tt>(A)</tt></td></tr>
  422. * <tr><th>3    </th>
  423. * <td><tt>(B(C))</tt></td></tr>
  424. * <tr><th>4    </th>
  425. * <td><tt>(C)</tt></td></tr>
  426. * </table></blockquote>
  427. *
  428. * <p> Group zero always stands for the entire expression.
  429. *
  430. * <p> Capturing groups are so named because, during a match, each subsequence
  431. * of the input sequence that matches such a group is saved. The captured
  432. * subsequence may be used later in the expression, via a back reference, and
  433. * may also be retrieved from the matcher once the match operation is complete.
  434. *
  435. * <p> The captured input associated with a group is always the subsequence
  436. * that the group most recently matched. If a group is evaluated a second time
  437. * because of quantification then its previously-captured value, if any, will
  438. * be retained if the second evaluation fails. Matching the string
  439. * <tt>"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves
  440. * group two set to <tt>"b"</tt>. All captured input is discarded at the
  441. * beginning of each match.
  442. *
  443. * <p> Groups beginning with <tt>(?</tt> are pure, <i>non-capturing</i> groups
  444. * that do not capture text and do not count towards the group total.
  445. *
  446. *
  447. * <h4> Unicode support </h4>
  448. *
  449. * <p> This class follows <a
  450. * href="http://www.unicode.org/unicode/reports/tr18/"><i>Unicode Technical
  451. * Report #18: Unicode Regular Expression Guidelines</i></a>, implementing its
  452. * second level of support though with a slightly different concrete syntax.
  453. *
  454. * <p> Unicode escape sequences such as <tt>\u2014</tt> in Java source code
  455. * are processed as described in <a
  456. * href="http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#100850">\u00A73.3</a>
  457. * of the Java Language Specification. Such escape sequences are also
  458. * implemented directly by the regular-expression parser so that Unicode
  459. * escapes can be used in expressions that are read from files or from the
  460. * keyboard. Thus the strings <tt>"\u2014"</tt> and <tt>"\\u2014"</tt>,
  461. * while not equal, compile into the same pattern, which matches the character
  462. * with hexadecimal value <tt>0x2014</tt>.
  463. *
  464. * <a name="ubc"> <p>Unicode blocks and categories are written with the
  465. * <tt>\p</tt> and <tt>\P</tt> constructs as in
  466. * Perl. <tt>\p{</tt><i>prop</i><tt>}</tt> matches if the input has the
  467. * property <i>prop</i>, while \P{</tt><i>prop</i><tt>}</tt> does not match if
  468. * the input has that property. Blocks are specified with the prefix
  469. * <tt>In</tt>, as in <tt>InMongolian</tt>. Categories may be specified with
  470. * the optional prefix <tt>Is</tt>: Both <tt>\p{L}</tt> and <tt>\p{IsL}</tt>
  471. * denote the category of Unicode letters. Blocks and categories can be used
  472. * both inside and outside of a character class.
  473. *
  474. * <p> The supported blocks and categories are those of <a
  475. * href="http://www.unicode.org/unicode/standard/standard.html"><i>The Unicode
  476. * Standard, Version 3.0</i></a>. The block names are those defined in
  477. * Chapter 14 and in the file <a
  478. * href="http://www.unicode.org/Public/3.0-Update/Blocks-3.txt">Blocks-3.txt
  479. * </a> of the <a
  480. * href="http://www.unicode.org/Public/3.0-Update/UnicodeCharacterDatabase-3.0.0.html">Unicode
  481. * Character Database</a> except that the spaces are removed; <tt>"Basic
  482. * Latin"</tt>, for example, becomes <tt>"BasicLatin"</tt>. The category names
  483. * are those defined in table 4-5 of the Standard (p. 88), both normative
  484. * and informative.
  485. *
  486. *
  487. * <h4> Comparison to Perl 5 </h4>
  488. *
  489. * <p> Perl constructs not supported by this class: </p>
  490. *
  491. * <ul>
  492. *
  493. * <li><p> The conditional constructs <tt>(?{</tt><i>X</i><tt>})</tt> and
  494. * <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>,
  495. * </p></li>
  496. *
  497. * <li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt>
  498. * and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li>
  499. *
  500. * <li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li>
  501. *
  502. * <li><p> The preprocessing operations <tt>\l</tt> <tt>\u</tt>,
  503. * <tt>\L</tt>, and <tt>\U</tt>. </p></li>
  504. *
  505. * </ul>
  506. *
  507. * <p> Constructs supported by this class but not by Perl: </p>
  508. *
  509. * <ul>
  510. *
  511. * <li><p> Possessive quantifiers, which greedily match as much as they can
  512. * and do not back off, even when doing so would allow the overall match to
  513. * succeed. </p></li>
  514. *
  515. * <li><p> Character-class union and intersection as described
  516. * <a href="#cc">above</a>.</p></li>
  517. *
  518. * </ul>
  519. *
  520. * <p> Notable differences from Perl: </p>
  521. *
  522. * <ul>
  523. *
  524. * <li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted
  525. * as back references; a backslash-escaped number greater than <tt>9</tt> is
  526. * treated as a back reference if at least that many subexpressions exist,
  527. * otherwise it is interpreted, if possible, as an octal escape. In this
  528. * class octal escapes must always begin with a zero. In this class,
  529. * <tt>\1</tt> through <tt>\9</tt> are always interpreted as back
  530. * references, and a larger number is accepted as a back reference if at
  531. * least that many subexpressions exist at that point in the regular
  532. * expression, otherwise the parser will drop digits until the number is
  533. * smaller or equal to the existing number of groups or it is one digit.
  534. * </p></li>
  535. *
  536. * <li><p> Perl uses the <tt>g</tt> flag to request a match that resumes
  537. * where the last match left off. This functionality is provided implicitly
  538. * by the {@link Matcher} class: Repeated invocations of the {@link
  539. * Matcher#find find} method will resume where the last match left off,
  540. * unless the matcher is reset. </p></li>
  541. *
  542. * <li><p> In Perl, embedded flags at the top level of an expression affect
  543. * the whole expression. In this class, embedded flags always take effect
  544. * at the point at which they appear, whether they are at the top level or
  545. * within a group; in the latter case, flags are restored at the end of the
  546. * group just as in Perl. </p></li>
  547. *
  548. * <li><p> Perl is forgiving about malformed matching constructs, as in the
  549. * expression <tt>*a</tt>, as well as dangling brackets, as in the
  550. * expression <tt>abc]</tt>, and treats them as literals. This
  551. * class also accepts dangling brackets but is strict about dangling
  552. * metacharacters like +, ? and *, and will throw a
  553. * {@link PatternSyntaxException} if it encounters them. </p></li>
  554. *
  555. * </ul>
  556. *
  557. *
  558. * <p> For a more precise description of the behavior of regular expression
  559. * constructs, please see <a href="http://www.oreilly.com/catalog/regex2/">
  560. * <i>Mastering Regular Expressions, 2nd Edition</i>, Jeffrey E. F. Friedl,
  561. * O'Reilly and Associates, 2002.</a>
  562. * </p>
  563. *
  564. * @see java.lang.String#split(String, int)
  565. * @see java.lang.String#split(String)
  566. *
  567. * @author Mike McCloskey
  568. * @author Mark Reinhold
  569. * @author JSR-51 Expert Group
  570. * @version 1.97, 04/01/13
  571. * @since 1.4
  572. * @spec JSR-51
  573. */
  574. public final class Pattern
  575. implements java.io.Serializable
  576. {
  577. /**
  578. * Regular expression modifier values. Instead of being passed as
  579. * arguments, they can also be passed as inline modifiers.
  580. * For example, the following statements have the same effect.
  581. * <pre>
  582. * RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M);
  583. * RegExp r2 = RegExp.compile("(?im)abc", 0);
  584. * </pre>
  585. *
  586. * The flags are duplicated so that the familiar Perl match flag
  587. * names are available.
  588. */
  589. /**
  590. * Enables Unix lines mode.
  591. *
  592. * <p> In this mode, only the <tt>'\n'</tt> line terminator is recognized
  593. * in the behavior of <tt>.</tt>, <tt>^</tt>, and <tt>$</tt>.
  594. *
  595. * <p> Unix lines mode can also be enabled via the embedded flag
  596. * expression <tt>(?d)</tt>.
  597. */
  598. public static final int UNIX_LINES = 0x01;
  599. /**
  600. * Enables case-insensitive matching.
  601. *
  602. * <p> By default, case-insensitive matching assumes that only characters
  603. * in the US-ASCII charset are being matched. Unicode-aware
  604. * case-insensitive matching can be enabled by specifying the {@link
  605. * #UNICODE_CASE} flag in conjunction with this flag.
  606. *
  607. * <p> Case-insensitive matching can also be enabled via the embedded flag
  608. * expression <tt>(?i)</tt>.
  609. *
  610. * <p> Specifying this flag may impose a slight performance penalty. </p>
  611. */
  612. public static final int CASE_INSENSITIVE = 0x02;
  613. /**
  614. * Permits whitespace and comments in pattern.
  615. *
  616. * <p> In this mode, whitespace is ignored, and embedded comments starting
  617. * with <tt>#</tt> are ignored until the end of a line.
  618. *
  619. * <p> Comments mode can also be enabled via the embedded flag
  620. * expression <tt>(?x)</tt>.
  621. */
  622. public static final int COMMENTS = 0x04;
  623. /**
  624. * Enables multiline mode.
  625. *
  626. * <p> In multiline mode the expressions <tt>^</tt> and <tt>$</tt> match
  627. * just after or just before, respectively, a line terminator or the end of
  628. * the input sequence. By default these expressions only match at the
  629. * beginning and the end of the entire input sequence.
  630. *
  631. * <p> Multiline mode can also be enabled via the embedded flag
  632. * expression <tt>(?m)</tt>. </p>
  633. */
  634. public static final int MULTILINE = 0x08;
  635. /**
  636. * Enables dotall mode.
  637. *
  638. * <p> In dotall mode, the expression <tt>.</tt> matches any character,
  639. * including a line terminator. By default this expression does not match
  640. * line terminators.
  641. *
  642. * <p> Dotall mode can also be enabled via the embedded flag
  643. * expression <tt>(?s)</tt>. (The <tt>s</tt> is a mnemonic for
  644. * "single-line" mode, which is what this is called in Perl.) </p>
  645. */
  646. public static final int DOTALL = 0x20;
  647. /**
  648. * Enables Unicode-aware case folding.
  649. *
  650. * <p> When this flag is specified then case-insensitive matching, when
  651. * enabled by the {@link #CASE_INSENSITIVE} flag, is done in a manner
  652. * consistent with the Unicode Standard. By default, case-insensitive
  653. * matching assumes that only characters in the US-ASCII charset are being
  654. * matched.
  655. *
  656. * <p> Unicode-aware case folding can also be enabled via the embedded flag
  657. * expression <tt>(?u)</tt>.
  658. *
  659. * <p> Specifying this flag may impose a performance penalty. </p>
  660. */
  661. public static final int UNICODE_CASE = 0x40;
  662. /**
  663. * Enables canonical equivalence.
  664. *
  665. * <p> When this flag is specified then two characters will be considered
  666. * to match if, and only if, their full canonical decompositions match.
  667. * The expression <tt>"a\u030A"</tt>, for example, will match the
  668. * string <tt>"\u00E5"</tt> when this flag is specified. By default,
  669. * matching does not take canonical equivalence into account.
  670. *
  671. * <p> There is no embedded flag character for enabling canonical
  672. * equivalence.
  673. *
  674. * <p> Specifying this flag may impose a performance penalty. </p>
  675. */
  676. public static final int CANON_EQ = 0x80;
  677. /* Pattern has only two serialized components: The pattern string
  678. * and the flags, which are all that is needed to recompile the pattern
  679. * when it is deserialized.
  680. */
  681. /** use serialVersionUID from Merlin b59 for interoperability */
  682. private static final long serialVersionUID = 5073258162644648461L;
  683. /**
  684. * The original regular-expression pattern string.
  685. *
  686. * @serial
  687. */
  688. private String pattern;
  689. /**
  690. * The original pattern flags.
  691. *
  692. * @serial
  693. */
  694. private int flags;
  695. /**
  696. * The normalized pattern string.
  697. */
  698. private transient String normalizedPattern;
  699. /**
  700. * The starting point of state machine for the find operation. This allows
  701. * a match to start anywhere in the input.
  702. */
  703. transient Node root;
  704. /**
  705. * The root of object tree for a match operation. The pattern is matched
  706. * at the beginning. This may include a find that uses BnM or a First
  707. * node.
  708. */
  709. transient Node matchRoot;
  710. /**
  711. * Temporary storage used by parsing pattern slice.
  712. */
  713. transient char[] buffer;
  714. /**
  715. * Temporary storage used while parsing group references.
  716. */
  717. transient GroupHead[] groupNodes;
  718. /**
  719. * Temporary null terminating char array used by pattern compiling.
  720. */
  721. private transient char[] temp;
  722. /**
  723. * The group count of this Pattern. Used by matchers to allocate storage
  724. * needed to perform a match.
  725. */
  726. transient int groupCount;
  727. /**
  728. * The local variable count used by parsing tree. Used by matchers to
  729. * allocate storage needed to perform a match.
  730. */
  731. transient int localCount;
  732. /**
  733. * Index into the pattern string that keeps track of how much has been
  734. * parsed.
  735. */
  736. private transient int cursor;
  737. /**
  738. * Holds the length of the pattern string.
  739. */
  740. private transient int patternLength;
  741. /**
  742. * Compiles the given regular expression into a pattern. </p>
  743. *
  744. * @param regex
  745. * The expression to be compiled
  746. *
  747. * @throws PatternSyntaxException
  748. * If the expression's syntax is invalid
  749. */
  750. public static Pattern compile(String regex) {
  751. return new Pattern(regex, 0);
  752. }
  753. /**
  754. * Compiles the given regular expression into a pattern with the given
  755. * flags. </p>
  756. *
  757. * @param regex
  758. * The expression to be compiled
  759. *
  760. * @param flags
  761. * Match flags, a bit mask that may include
  762. * {@link #CASE_INSENSITIVE}, {@link #MULTILINE}, {@link #DOTALL},
  763. * {@link #UNICODE_CASE}, and {@link #CANON_EQ}
  764. *
  765. * @throws IllegalArgumentException
  766. * If bit values other than those corresponding to the defined
  767. * match flags are set in <tt>flags</tt>
  768. *
  769. * @throws PatternSyntaxException
  770. * If the expression's syntax is invalid
  771. */
  772. public static Pattern compile(String regex, int flags) {
  773. return new Pattern(regex, flags);
  774. }
  775. /**
  776. * Returns the regular expression from which this pattern was compiled.
  777. * </p>
  778. *
  779. * @return The source of this pattern
  780. */
  781. public String pattern() {
  782. return pattern;
  783. }
  784. /**
  785. * Creates a matcher that will match the given input against this pattern.
  786. * </p>
  787. *
  788. * @param input
  789. * The character sequence to be matched
  790. *
  791. * @return A new matcher for this pattern
  792. */
  793. public Matcher matcher(CharSequence input) {
  794. Matcher m = new Matcher(this, input);
  795. return m;
  796. }
  797. /**
  798. * Returns this pattern's match flags. </p>
  799. *
  800. * @return The match flags specified when this pattern was compiled
  801. */
  802. public int flags() {
  803. return flags;
  804. }
  805. /**
  806. * Compiles the given regular expression and attempts to match the given
  807. * input against it.
  808. *
  809. * <p> An invocation of this convenience method of the form
  810. *
  811. * <blockquote><pre>
  812. * Pattern.matches(regex, input);</pre></blockquote>
  813. *
  814. * behaves in exactly the same way as the expression
  815. *
  816. * <blockquote><pre>
  817. * Pattern.compile(regex).matcher(input).matches()</pre></blockquote>
  818. *
  819. * <p> If a pattern is to be used multiple times, compiling it once and reusing
  820. * it will be more efficient than invoking this method each time. </p>
  821. *
  822. * @param regex
  823. * The expression to be compiled
  824. *
  825. * @param input
  826. * The character sequence to be matched
  827. *
  828. * @throws PatternSyntaxException
  829. * If the expression's syntax is invalid
  830. */
  831. public static boolean matches(String regex, CharSequence input) {
  832. Pattern p = Pattern.compile(regex);
  833. Matcher m = p.matcher(input);
  834. return m.matches();
  835. }
  836. /**
  837. * Splits the given input sequence around matches of this pattern.
  838. *
  839. * <p> The array returned by this method contains each substring of the
  840. * input sequence that is terminated by another subsequence that matches
  841. * this pattern or is terminated by the end of the input sequence. The
  842. * substrings in the array are in the order in which they occur in the
  843. * input. If this pattern does not match any subsequence of the input then
  844. * the resulting array has just one element, namely the input sequence in
  845. * string form.
  846. *
  847. * <p> The <tt>limit</tt> parameter controls the number of times the
  848. * pattern is applied and therefore affects the length of the resulting
  849. * array. If the limit <i>n</i> is greater than zero then the pattern
  850. * will be applied at most <i>n</i> - 1 times, the array's
  851. * length will be no greater than <i>n</i>, and the array's last entry
  852. * will contain all input beyond the last matched delimiter. If <i>n</i>
  853. * is non-positive then the pattern will be applied as many times as
  854. * possible and the array can have any length. If <i>n</i> is zero then
  855. * the pattern will be applied as many times as possible, the array can
  856. * have any length, and trailing empty strings will be discarded.
  857. *
  858. * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
  859. * results with these parameters:
  860. *
  861. * <blockquote><table cellpadding=1 cellspacing=0
  862. * summary="Split examples showing regex, limit, and result">
  863. * <tr><th><P align="left"><i>Regex    </i></th>
  864. * <th><P align="left"><i>Limit    </i></th>
  865. * <th><P align="left"><i>Result    </i></th></tr>
  866. * <tr><td align=center>:</td>
  867. * <td align=center>2</td>
  868. * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
  869. * <tr><td align=center>:</td>
  870. * <td align=center>5</td>
  871. * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  872. * <tr><td align=center>:</td>
  873. * <td align=center>-2</td>
  874. * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  875. * <tr><td align=center>o</td>
  876. * <td align=center>5</td>
  877. * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
  878. * <tr><td align=center>o</td>
  879. * <td align=center>-2</td>
  880. * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
  881. * <tr><td align=center>o</td>
  882. * <td align=center>0</td>
  883. * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
  884. * </table></blockquote>
  885. *
  886. *
  887. * @param input
  888. * The character sequence to be split
  889. *
  890. * @param limit
  891. * The result threshold, as described above
  892. *
  893. * @return The array of strings computed by splitting the input
  894. * around matches of this pattern
  895. */
  896. public String[] split(CharSequence input, int limit) {
  897. int index = 0;
  898. boolean matchLimited = limit > 0;
  899. ArrayList matchList = new ArrayList();
  900. Matcher m = matcher(input);
  901. // Add segments before each match found
  902. while(m.find()) {
  903. if (!matchLimited || matchList.size() < limit - 1) {
  904. String match = input.subSequence(index, m.start()).toString();
  905. matchList.add(match);
  906. index = m.end();
  907. } else if (matchList.size() == limit - 1) { // last one
  908. String match = input.subSequence(index,
  909. input.length()).toString();
  910. matchList.add(match);
  911. index = m.end();
  912. }
  913. }
  914. // If no match was found, return this
  915. if (index == 0)
  916. return new String[] {input.toString()};
  917. // Add remaining segment
  918. if (!matchLimited || matchList.size() < limit)
  919. matchList.add(input.subSequence(index, input.length()).toString());
  920. // Construct result
  921. int resultSize = matchList.size();
  922. if (limit == 0)
  923. while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
  924. resultSize--;
  925. String[] result = new String[resultSize];
  926. return (String[])matchList.subList(0, resultSize).toArray(result);
  927. }
  928. /**
  929. * Splits the given input sequence around matches of this pattern.
  930. *
  931. * <p> This method works as if by invoking the two-argument {@link
  932. * #split(java.lang.CharSequence, int) split} method with the given input
  933. * sequence and a limit argument of zero. Trailing empty strings are
  934. * therefore not included in the resulting array. </p>
  935. *
  936. * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
  937. * results with these expressions:
  938. *
  939. * <blockquote><table cellpadding=1 cellspacing=0
  940. * summary="Split examples showing regex and result">
  941. * <tr><th><P align="left"><i>Regex    </i></th>
  942. * <th><P align="left"><i>Result</i></th></tr>
  943. * <tr><td align=center>:</td>
  944. * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  945. * <tr><td align=center>o</td>
  946. * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
  947. * </table></blockquote>
  948. *
  949. *
  950. * @param input
  951. * The character sequence to be split
  952. *
  953. * @return The array of strings computed by splitting the input
  954. * around matches of this pattern
  955. */
  956. public String[] split(CharSequence input) {
  957. return split(input, 0);
  958. }
  959. /**
  960. * Recompile the Pattern instance from a stream. The original pattern
  961. * string is read in and the object tree is recompiled from it.
  962. */
  963. private void readObject(java.io.ObjectInputStream s)
  964. throws java.io.IOException, ClassNotFoundException {
  965. // Read in all fields
  966. s.defaultReadObject();
  967. // Initialize counts
  968. groupCount = 1;
  969. localCount = 0;
  970. // Recompile object tree
  971. if (pattern.length() > 0)
  972. compile();
  973. else
  974. root = new Start(lastAccept);
  975. }
  976. /**
  977. * This private constructor is used to create all Patterns. The pattern
  978. * string and match flags are all that is needed to completely describe
  979. * a Pattern. An empty pattern string results in an object tree with
  980. * only a Start node and a LastNode node.
  981. */
  982. private Pattern(String p, int f) {
  983. pattern = p;
  984. flags = f;
  985. // Reset group index count
  986. groupCount = 1;
  987. localCount = 0;
  988. if (pattern.length() > 0) {
  989. compile();
  990. } else {
  991. root = new Start(lastAccept);
  992. matchRoot = lastAccept;
  993. }
  994. }
  995. /**
  996. * The pattern is converted to normalizedD form and then a pure group
  997. * is constructed to match canonical equivalences of the characters.
  998. */
  999. private void normalize() {
  1000. boolean inCharClass = false;
  1001. char lastChar = 0xffff;
  1002. // Convert pattern into normalizedD form
  1003. normalizedPattern = Normalizer.decompose(pattern, false, 0);
  1004. patternLength = normalizedPattern.length();
  1005. // Modify pattern to match canonical equivalences
  1006. StringBuffer newPattern = new StringBuffer(patternLength);
  1007. for(int i=0; i<patternLength; i++) {
  1008. char c = normalizedPattern.charAt(i);
  1009. StringBuffer sequenceBuffer;
  1010. if ((Character.getType(c) == Character.NON_SPACING_MARK)
  1011. && (lastChar != 0xffff)) {
  1012. sequenceBuffer = new StringBuffer();
  1013. sequenceBuffer.append(lastChar);
  1014. sequenceBuffer.append(c);
  1015. while(Character.getType(c) == Character.NON_SPACING_MARK) {
  1016. i++;
  1017. if (i >= patternLength)
  1018. break;
  1019. c = normalizedPattern.charAt(i);
  1020. sequenceBuffer.append(c);
  1021. }
  1022. String ea = produceEquivalentAlternation(
  1023. sequenceBuffer.toString());
  1024. newPattern.setLength(newPattern.length()-1);
  1025. newPattern.append("(?:").append(ea).append(")");
  1026. } else if (c == '[' && lastChar != '\\') {
  1027. i = normalizeCharClass(newPattern, i);
  1028. } else {
  1029. newPattern.append(c);
  1030. }
  1031. lastChar = c;
  1032. }
  1033. normalizedPattern = newPattern.toString();
  1034. }
  1035. /**
  1036. * Complete the character class being parsed and add a set
  1037. * of alternations to it that will match the canonical equivalences
  1038. * of the characters within the class.
  1039. */
  1040. private int normalizeCharClass(StringBuffer newPattern, int i) {
  1041. StringBuffer charClass = new StringBuffer();
  1042. StringBuffer eq = null;
  1043. char lastChar = 0xffff;
  1044. String result;
  1045. i++;
  1046. charClass.append("[");
  1047. while(true) {
  1048. char c = normalizedPattern.charAt(i);
  1049. StringBuffer sequenceBuffer;
  1050. if (c == ']' && lastChar != '\\') {
  1051. charClass.append(c);
  1052. break;
  1053. } else if (Character.getType(c) == Character.NON_SPACING_MARK) {
  1054. sequenceBuffer = new StringBuffer();
  1055. sequenceBuffer.append(lastChar);
  1056. while(Character.getType(c) == Character.NON_SPACING_MARK) {
  1057. sequenceBuffer.append(c);
  1058. i++;
  1059. if (i >= normalizedPattern.length())
  1060. break;
  1061. c = normalizedPattern.charAt(i);
  1062. }
  1063. String ea = produceEquivalentAlternation(
  1064. sequenceBuffer.toString());
  1065. charClass.setLength(charClass.length()-1);
  1066. if (eq == null)
  1067. eq = new StringBuffer();
  1068. eq.append('|');
  1069. eq.append(ea);
  1070. } else {
  1071. charClass.append(c);
  1072. i++;
  1073. }
  1074. if (i == normalizedPattern.length())
  1075. error("Unclosed character class");
  1076. lastChar = c;
  1077. }
  1078. if (eq != null) {
  1079. result = new String("(?:"+charClass.toString()+
  1080. eq.toString()+")");
  1081. } else {
  1082. result = charClass.toString();
  1083. }
  1084. newPattern.append(result);
  1085. return i;
  1086. }
  1087. /**
  1088. * Given a specific sequence composed of a regular character and
  1089. * combining marks that follow it, produce the alternation that will
  1090. * match all canonical equivalences of that sequence.
  1091. */
  1092. private String produceEquivalentAlternation(String source) {
  1093. if (source.length() == 1)
  1094. return new String(source);
  1095. String base = source.substring(0,1);
  1096. String combiningMarks = source.substring(1);
  1097. String[] perms = producePermutations(combiningMarks);
  1098. StringBuffer result = new StringBuffer(source);
  1099. // Add combined permutations
  1100. for(int x=0; x<perms.length; x++) {
  1101. String next = base + perms[x];
  1102. if (x>0)
  1103. result.append("|"+next);
  1104. next = composeOneStep(next);
  1105. if (next != null)
  1106. result.append("|"+produceEquivalentAlternation(next));
  1107. }
  1108. return result.toString();
  1109. }
  1110. /**
  1111. * Returns an array of strings that have all the possible
  1112. * permutations of the characters in the input string.
  1113. * This is used to get a list of all possible orderings
  1114. * of a set of combining marks. Note that some of the permutations
  1115. * are invalid because of combining class collisions, and these
  1116. * possibilities must be removed because they are not canonically
  1117. * equivalent.
  1118. */
  1119. private String[] producePermutations(String input) {
  1120. if (input.length() == 1)
  1121. return new String[] {input};
  1122. if (input.length() == 2) {
  1123. if (getClass(input.charAt(1)) ==
  1124. getClass(input.charAt(0))) {
  1125. return new String[] {input};
  1126. }
  1127. String[] result = new String[2];
  1128. result[0] = input;
  1129. StringBuffer sb = new StringBuffer(2);
  1130. sb.append(input.charAt(1));
  1131. sb.append(input.charAt(0));
  1132. result[1] = sb.toString();
  1133. return result;
  1134. }
  1135. int length = 1;
  1136. for(int x=1; x<input.length(); x++)
  1137. length = length * (x+1);
  1138. String[] temp = new String[length];
  1139. int combClass[] = new int[input.length()];
  1140. for(int x=0; x<input.length(); x++)
  1141. combClass[x] = getClass(input.charAt(x));
  1142. // For each char, take it out and add the permutations
  1143. // of the remaining chars
  1144. int index = 0;
  1145. loop: for(int x=0; x<input.length(); x++) {
  1146. boolean skip = false;
  1147. for(int y=x-1; y>=0; y--) {
  1148. if (combClass[y] == combClass[x]) {
  1149. continue loop;
  1150. }
  1151. }
  1152. StringBuffer sb = new StringBuffer(input);
  1153. String otherChars = sb.delete(x, x+1).toString();
  1154. String[] subResult = producePermutations(otherChars);
  1155. String prefix = input.substring(x, x+1);
  1156. for(int y=0; y<subResult.length; y++)
  1157. temp[index++] = prefix + subResult[y];
  1158. }
  1159. String[] result = new String[index];
  1160. for (int x=0; x<index; x++)
  1161. result[x] = temp[x];
  1162. return result;
  1163. }
  1164. private int getClass(char c) {
  1165. return Normalizer.getClass(c);
  1166. }
  1167. /**
  1168. * Attempts to compose input by combining the first character
  1169. * with the first combining mark following it. Returns a String
  1170. * that is the composition of the leading character with its first
  1171. * combining mark followed by the remaining combining marks. Returns
  1172. * null if the first two chars cannot be further composed.
  1173. */
  1174. private String composeOneStep(String input) {
  1175. String firstTwoChars = input.substring(0,2);
  1176. String result = Normalizer.compose(firstTwoChars, false, 0);
  1177. if (result.equals(firstTwoChars))
  1178. return null;
  1179. else {
  1180. String remainder = input.substring(2);
  1181. return result + remainder;
  1182. }
  1183. }
  1184. /**
  1185. * Copies regular expression to a char array and inovkes the parsing
  1186. * of the expression which will create the object tree.
  1187. */
  1188. private void compile() {
  1189. // Handle canonical equivalences
  1190. if (has(CANON_EQ)) {
  1191. normalize();
  1192. } else {
  1193. normalizedPattern = pattern;
  1194. }
  1195. // Copy pattern to char array for convenience
  1196. patternLength = normalizedPattern.length();
  1197. temp = new char[patternLength + 2];
  1198. // Use double null characters to terminate pattern
  1199. normalizedPattern.getChars(0, patternLength, temp, 0);
  1200. temp[patternLength] = 0;
  1201. temp[patternLength + 1] = 0;
  1202. // Allocate all temporary objects here.
  1203. buffer = new char[32];
  1204. groupNodes = new GroupHead[10];
  1205. // Start recursive decedent parsing
  1206. matchRoot = expr(lastAccept);
  1207. // Check extra pattern characters
  1208. if (patternLength != cursor) {
  1209. if (peek() == ')') {
  1210. error("Unmatched closing ')'");
  1211. } else {
  1212. error("Unexpected internal error");
  1213. }
  1214. }
  1215. // Peephole optimization
  1216. if (matchRoot instanceof Slice) {
  1217. root = BnM.optimize(matchRoot);
  1218. if (root == matchRoot) {
  1219. root = new Start(matchRoot);
  1220. }
  1221. } else if (matchRoot instanceof Begin
  1222. || matchRoot instanceof First) {
  1223. root = matchRoot;
  1224. } else {
  1225. root = new Start(matchRoot);
  1226. }
  1227. // Release temporary storage
  1228. temp = null;
  1229. buffer = null;
  1230. groupNodes = null;
  1231. patternLength = 0;
  1232. }
  1233. /**
  1234. * Used to print out a subtree of the Pattern to help with debugging.
  1235. */
  1236. private static void printObjectTree(Node node) {
  1237. while(node != null) {
  1238. if (node instanceof Prolog) {
  1239. System.out.println(node);
  1240. printObjectTree(((Prolog)node).loop);
  1241. System.out.println("**** end contents prolog loop");
  1242. } else if (node instanceof Loop) {
  1243. System.out.println(node);
  1244. printObjectTree(((Loop)node).body);
  1245. System.out.println("**** end contents Loop body");
  1246. } else if (node instanceof Curly) {
  1247. System.out.println(node);
  1248. printObjectTree(((Curly)node).atom);
  1249. System.out.println("**** end contents Curly body");
  1250. } else if (node instanceof GroupTail) {
  1251. System.out.println(node);
  1252. System.out.println("Tail next is "+node.next);
  1253. return;
  1254. } else {
  1255. System.out.println(node);
  1256. }
  1257. node = node.next;
  1258. if (node != null)
  1259. System.out.println("->next:");
  1260. if (node == Pattern.accept) {
  1261. System.out.println("Accept Node");
  1262. node = null;
  1263. }
  1264. }
  1265. }
  1266. /**
  1267. * Used to accumulate information about a subtree of the object graph
  1268. * so that optimizations can be applied to the subtree.
  1269. */
  1270. static final class TreeInfo {
  1271. int minLength;
  1272. int maxLength;
  1273. boolean maxValid;
  1274. boolean deterministic;
  1275. TreeInfo() {
  1276. reset();
  1277. }
  1278. void reset() {
  1279. minLength = 0;
  1280. maxLength = 0;
  1281. maxValid = true;
  1282. deterministic = true;
  1283. }
  1284. }
  1285. /**
  1286. * The following private methods are mainly used to improve the
  1287. * readability of the code. In order to let the Java compiler easily
  1288. * inline them, we should not put many assertions or error checks in them.
  1289. */
  1290. /**
  1291. * Indicates whether a particular flag is set or not.
  1292. */
  1293. private boolean has(int f) {
  1294. return (flags & f) > 0;
  1295. }
  1296. /**
  1297. * Match next character, signal error if failed.
  1298. */
  1299. private void accept(int ch, String s) {
  1300. int testChar = temp[cursor++];
  1301. if (has(COMMENTS))
  1302. testChar = parsePastWhitespace(testChar);
  1303. if (ch != testChar) {
  1304. error(s);
  1305. }
  1306. }
  1307. /**
  1308. * Mark the end of pattern with a specific character.
  1309. */
  1310. private void mark(char c) {
  1311. temp[patternLength] = c;
  1312. }
  1313. /**
  1314. * Peek the next character, and do not advance the cursor.
  1315. */
  1316. private int peek() {
  1317. int ch = temp[cursor];
  1318. if (has(COMMENTS))
  1319. ch = peekPastWhi