PageRenderTime 97ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/java-1.7.0-openjdk/openjdk/jdk/src/share/classes/java/util/regex/Pattern.java

#
Java | 5648 lines | 3493 code | 292 blank | 1863 comment | 904 complexity | 6489a95a7f4c9de11ec05042f9397af3 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause-No-Nuclear-License-2014, LGPL-3.0, LGPL-2.0
  1. /*
  2. * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
  3. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. *
  5. * This code is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License version 2 only, as
  7. * published by the Free Software Foundation. Oracle designates this
  8. * particular file as subject to the "Classpath" exception as provided
  9. * by Oracle in the LICENSE file that accompanied this code.
  10. *
  11. * This code is distributed in the hope that it will be useful, but WITHOUT
  12. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
  14. * version 2 for more details (a copy is included in the LICENSE file that
  15. * accompanied this code).
  16. *
  17. * You should have received a copy of the GNU General Public License version
  18. * 2 along with this work; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20. *
  21. * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22. * or visit www.oracle.com if you need additional information or have any
  23. * questions.
  24. */
  25. package java.util.regex;
  26. import java.security.AccessController;
  27. import java.security.PrivilegedAction;
  28. import java.text.CharacterIterator;
  29. import java.text.Normalizer;
  30. import java.util.Locale;
  31. import java.util.Map;
  32. import java.util.ArrayList;
  33. import java.util.HashMap;
  34. import java.util.Arrays;
  35. /**
  36. * A compiled representation of a regular expression.
  37. *
  38. * <p> A regular expression, specified as a string, must first be compiled into
  39. * an instance of this class. The resulting pattern can then be used to create
  40. * a {@link Matcher} object that can match arbitrary {@link
  41. * java.lang.CharSequence </code>character sequences<code>} against the regular
  42. * expression. All of the state involved in performing a match resides in the
  43. * matcher, so many matchers can share the same pattern.
  44. *
  45. * <p> A typical invocation sequence is thus
  46. *
  47. * <blockquote><pre>
  48. * Pattern p = Pattern.{@link #compile compile}("a*b");
  49. * Matcher m = p.{@link #matcher matcher}("aaaaab");
  50. * boolean b = m.{@link Matcher#matches matches}();</pre></blockquote>
  51. *
  52. * <p> A {@link #matches matches} method is defined by this class as a
  53. * convenience for when a regular expression is used just once. This method
  54. * compiles an expression and matches an input sequence against it in a single
  55. * invocation. The statement
  56. *
  57. * <blockquote><pre>
  58. * boolean b = Pattern.matches("a*b", "aaaaab");</pre></blockquote>
  59. *
  60. * is equivalent to the three statements above, though for repeated matches it
  61. * is less efficient since it does not allow the compiled pattern to be reused.
  62. *
  63. * <p> Instances of this class are immutable and are safe for use by multiple
  64. * concurrent threads. Instances of the {@link Matcher} class are not safe for
  65. * such use.
  66. *
  67. *
  68. * <a name="sum">
  69. * <h4> Summary of regular-expression constructs </h4>
  70. *
  71. * <table border="0" cellpadding="1" cellspacing="0"
  72. * summary="Regular expression constructs, and what they match">
  73. *
  74. * <tr align="left">
  75. * <th bgcolor="#CCCCFF" align="left" id="construct">Construct</th>
  76. * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th>
  77. * </tr>
  78. *
  79. * <tr><th>&nbsp;</th></tr>
  80. * <tr align="left"><th colspan="2" id="characters">Characters</th></tr>
  81. *
  82. * <tr><td valign="top" headers="construct characters"><i>x</i></td>
  83. * <td headers="matches">The character <i>x</i></td></tr>
  84. * <tr><td valign="top" headers="construct characters"><tt>\\</tt></td>
  85. * <td headers="matches">The backslash character</td></tr>
  86. * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>n</i></td>
  87. * <td headers="matches">The character with octal value <tt>0</tt><i>n</i>
  88. * (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr>
  89. * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>nn</i></td>
  90. * <td headers="matches">The character with octal value <tt>0</tt><i>nn</i>
  91. * (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr>
  92. * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>mnn</i></td>
  93. * <td headers="matches">The character with octal value <tt>0</tt><i>mnn</i>
  94. * (0&nbsp;<tt>&lt;=</tt>&nbsp;<i>m</i>&nbsp;<tt>&lt;=</tt>&nbsp;3,
  95. * 0&nbsp;<tt>&lt;=</tt>&nbsp;<i>n</i>&nbsp;<tt>&lt;=</tt>&nbsp;7)</td></tr>
  96. * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>hh</i></td>
  97. * <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>hh</i></td></tr>
  98. * <tr><td valign="top" headers="construct characters"><tt>&#92;u</tt><i>hhhh</i></td>
  99. * <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>hhhh</i></td></tr>
  100. * <tr><td valign="top" headers="construct characters"><tt>&#92;x</tt><i>{h...h}</i></td>
  101. * <td headers="matches">The character with hexadecimal&nbsp;value&nbsp;<tt>0x</tt><i>h...h</i>
  102. * ({@link java.lang.Character#MIN_CODE_POINT Character.MIN_CODE_POINT}
  103. * &nbsp;&lt;=&nbsp;<tt>0x</tt><i>h...h</i>&nbsp;&lt;=&nbsp
  104. * {@link java.lang.Character#MAX_CODE_POINT Character.MAX_CODE_POINT})</td></tr>
  105. * <tr><td valign="top" headers="matches"><tt>\t</tt></td>
  106. * <td headers="matches">The tab character (<tt>'&#92;u0009'</tt>)</td></tr>
  107. * <tr><td valign="top" headers="construct characters"><tt>\n</tt></td>
  108. * <td headers="matches">The newline (line feed) character (<tt>'&#92;u000A'</tt>)</td></tr>
  109. * <tr><td valign="top" headers="construct characters"><tt>\r</tt></td>
  110. * <td headers="matches">The carriage-return character (<tt>'&#92;u000D'</tt>)</td></tr>
  111. * <tr><td valign="top" headers="construct characters"><tt>\f</tt></td>
  112. * <td headers="matches">The form-feed character (<tt>'&#92;u000C'</tt>)</td></tr>
  113. * <tr><td valign="top" headers="construct characters"><tt>\a</tt></td>
  114. * <td headers="matches">The alert (bell) character (<tt>'&#92;u0007'</tt>)</td></tr>
  115. * <tr><td valign="top" headers="construct characters"><tt>\e</tt></td>
  116. * <td headers="matches">The escape character (<tt>'&#92;u001B'</tt>)</td></tr>
  117. * <tr><td valign="top" headers="construct characters"><tt>\c</tt><i>x</i></td>
  118. * <td headers="matches">The control character corresponding to <i>x</i></td></tr>
  119. *
  120. * <tr><th>&nbsp;</th></tr>
  121. * <tr align="left"><th colspan="2" id="classes">Character classes</th></tr>
  122. *
  123. * <tr><td valign="top" headers="construct classes"><tt>[abc]</tt></td>
  124. * <td headers="matches"><tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (simple class)</td></tr>
  125. * <tr><td valign="top" headers="construct classes"><tt>[^abc]</tt></td>
  126. * <td headers="matches">Any character except <tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (negation)</td></tr>
  127. * <tr><td valign="top" headers="construct classes"><tt>[a-zA-Z]</tt></td>
  128. * <td headers="matches"><tt>a</tt> through <tt>z</tt>
  129. * or <tt>A</tt> through <tt>Z</tt>, inclusive (range)</td></tr>
  130. * <tr><td valign="top" headers="construct classes"><tt>[a-d[m-p]]</tt></td>
  131. * <td headers="matches"><tt>a</tt> through <tt>d</tt>,
  132. * or <tt>m</tt> through <tt>p</tt>: <tt>[a-dm-p]</tt> (union)</td></tr>
  133. * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[def]]</tt></td>
  134. * <td headers="matches"><tt>d</tt>, <tt>e</tt>, or <tt>f</tt> (intersection)</tr>
  135. * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^bc]]</tt></td>
  136. * <td headers="matches"><tt>a</tt> through <tt>z</tt>,
  137. * except for <tt>b</tt> and <tt>c</tt>: <tt>[ad-z]</tt> (subtraction)</td></tr>
  138. * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^m-p]]</tt></td>
  139. * <td headers="matches"><tt>a</tt> through <tt>z</tt>,
  140. * and not <tt>m</tt> through <tt>p</tt>: <tt>[a-lq-z]</tt>(subtraction)</td></tr>
  141. * <tr><th>&nbsp;</th></tr>
  142. *
  143. * <tr align="left"><th colspan="2" id="predef">Predefined character classes</th></tr>
  144. *
  145. * <tr><td valign="top" headers="construct predef"><tt>.</tt></td>
  146. * <td headers="matches">Any character (may or may not match <a href="#lt">line terminators</a>)</td></tr>
  147. * <tr><td valign="top" headers="construct predef"><tt>\d</tt></td>
  148. * <td headers="matches">A digit: <tt>[0-9]</tt></td></tr>
  149. * <tr><td valign="top" headers="construct predef"><tt>\D</tt></td>
  150. * <td headers="matches">A non-digit: <tt>[^0-9]</tt></td></tr>
  151. * <tr><td valign="top" headers="construct predef"><tt>\s</tt></td>
  152. * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
  153. * <tr><td valign="top" headers="construct predef"><tt>\S</tt></td>
  154. * <td headers="matches">A non-whitespace character: <tt>[^\s]</tt></td></tr>
  155. * <tr><td valign="top" headers="construct predef"><tt>\w</tt></td>
  156. * <td headers="matches">A word character: <tt>[a-zA-Z_0-9]</tt></td></tr>
  157. * <tr><td valign="top" headers="construct predef"><tt>\W</tt></td>
  158. * <td headers="matches">A non-word character: <tt>[^\w]</tt></td></tr>
  159. *
  160. * <tr><th>&nbsp;</th></tr>
  161. * <tr align="left"><th colspan="2" id="posix">POSIX character classes</b> (US-ASCII only)<b></th></tr>
  162. *
  163. * <tr><td valign="top" headers="construct posix"><tt>\p{Lower}</tt></td>
  164. * <td headers="matches">A lower-case alphabetic character: <tt>[a-z]</tt></td></tr>
  165. * <tr><td valign="top" headers="construct posix"><tt>\p{Upper}</tt></td>
  166. * <td headers="matches">An upper-case alphabetic character:<tt>[A-Z]</tt></td></tr>
  167. * <tr><td valign="top" headers="construct posix"><tt>\p{ASCII}</tt></td>
  168. * <td headers="matches">All ASCII:<tt>[\x00-\x7F]</tt></td></tr>
  169. * <tr><td valign="top" headers="construct posix"><tt>\p{Alpha}</tt></td>
  170. * <td headers="matches">An alphabetic character:<tt>[\p{Lower}\p{Upper}]</tt></td></tr>
  171. * <tr><td valign="top" headers="construct posix"><tt>\p{Digit}</tt></td>
  172. * <td headers="matches">A decimal digit: <tt>[0-9]</tt></td></tr>
  173. * <tr><td valign="top" headers="construct posix"><tt>\p{Alnum}</tt></td>
  174. * <td headers="matches">An alphanumeric character:<tt>[\p{Alpha}\p{Digit}]</tt></td></tr>
  175. * <tr><td valign="top" headers="construct posix"><tt>\p{Punct}</tt></td>
  176. * <td headers="matches">Punctuation: One of <tt>!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~</tt></td></tr>
  177. * <!-- <tt>[\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]</tt>
  178. * <tt>[\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]</tt> -->
  179. * <tr><td valign="top" headers="construct posix"><tt>\p{Graph}</tt></td>
  180. * <td headers="matches">A visible character: <tt>[\p{Alnum}\p{Punct}]</tt></td></tr>
  181. * <tr><td valign="top" headers="construct posix"><tt>\p{Print}</tt></td>
  182. * <td headers="matches">A printable character: <tt>[\p{Graph}\x20]</tt></td></tr>
  183. * <tr><td valign="top" headers="construct posix"><tt>\p{Blank}</tt></td>
  184. * <td headers="matches">A space or a tab: <tt>[ \t]</tt></td></tr>
  185. * <tr><td valign="top" headers="construct posix"><tt>\p{Cntrl}</tt></td>
  186. * <td headers="matches">A control character: <tt>[\x00-\x1F\x7F]</tt></td></tr>
  187. * <tr><td valign="top" headers="construct posix"><tt>\p{XDigit}</tt></td>
  188. * <td headers="matches">A hexadecimal digit: <tt>[0-9a-fA-F]</tt></td></tr>
  189. * <tr><td valign="top" headers="construct posix"><tt>\p{Space}</tt></td>
  190. * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
  191. *
  192. * <tr><th>&nbsp;</th></tr>
  193. * <tr align="left"><th colspan="2">java.lang.Character classes (simple <a href="#jcc">java character type</a>)</th></tr>
  194. *
  195. * <tr><td valign="top"><tt>\p{javaLowerCase}</tt></td>
  196. * <td>Equivalent to java.lang.Character.isLowerCase()</td></tr>
  197. * <tr><td valign="top"><tt>\p{javaUpperCase}</tt></td>
  198. * <td>Equivalent to java.lang.Character.isUpperCase()</td></tr>
  199. * <tr><td valign="top"><tt>\p{javaWhitespace}</tt></td>
  200. * <td>Equivalent to java.lang.Character.isWhitespace()</td></tr>
  201. * <tr><td valign="top"><tt>\p{javaMirrored}</tt></td>
  202. * <td>Equivalent to java.lang.Character.isMirrored()</td></tr>
  203. *
  204. * <tr><th>&nbsp;</th></tr>
  205. * <tr align="left"><th colspan="2" id="unicode">Classes for Unicode scripts, blocks, categories and binary properties</th></tr>
  206. * * <tr><td valign="top" headers="construct unicode"><tt>\p{IsLatin}</tt></td>
  207. * <td headers="matches">A Latin&nbsp;script character (<a href="#usc">script</a>)</td></tr>
  208. * <tr><td valign="top" headers="construct unicode"><tt>\p{InGreek}</tt></td>
  209. * <td headers="matches">A character in the Greek&nbsp;block (<a href="#ubc">block</a>)</td></tr>
  210. * <tr><td valign="top" headers="construct unicode"><tt>\p{Lu}</tt></td>
  211. * <td headers="matches">An uppercase letter (<a href="#ucc">category</a>)</td></tr>
  212. * <tr><td valign="top" headers="construct unicode"><tt>\p{IsAlphabetic}</tt></td>
  213. * <td headers="matches">An alphabetic character (<a href="#ubpc">binary property</a>)</td></tr>
  214. * <tr><td valign="top" headers="construct unicode"><tt>\p{Sc}</tt></td>
  215. * <td headers="matches">A currency symbol</td></tr>
  216. * <tr><td valign="top" headers="construct unicode"><tt>\P{InGreek}</tt></td>
  217. * <td headers="matches">Any character except one in the Greek block (negation)</td></tr>
  218. * <tr><td valign="top" headers="construct unicode"><tt>[\p{L}&&[^\p{Lu}]]&nbsp;</tt></td>
  219. * <td headers="matches">Any letter except an uppercase letter (subtraction)</td></tr>
  220. *
  221. * <tr><th>&nbsp;</th></tr>
  222. * <tr align="left"><th colspan="2" id="bounds">Boundary matchers</th></tr>
  223. *
  224. * <tr><td valign="top" headers="construct bounds"><tt>^</tt></td>
  225. * <td headers="matches">The beginning of a line</td></tr>
  226. * <tr><td valign="top" headers="construct bounds"><tt>$</tt></td>
  227. * <td headers="matches">The end of a line</td></tr>
  228. * <tr><td valign="top" headers="construct bounds"><tt>\b</tt></td>
  229. * <td headers="matches">A word boundary</td></tr>
  230. * <tr><td valign="top" headers="construct bounds"><tt>\B</tt></td>
  231. * <td headers="matches">A non-word boundary</td></tr>
  232. * <tr><td valign="top" headers="construct bounds"><tt>\A</tt></td>
  233. * <td headers="matches">The beginning of the input</td></tr>
  234. * <tr><td valign="top" headers="construct bounds"><tt>\G</tt></td>
  235. * <td headers="matches">The end of the previous match</td></tr>
  236. * <tr><td valign="top" headers="construct bounds"><tt>\Z</tt></td>
  237. * <td headers="matches">The end of the input but for the final
  238. * <a href="#lt">terminator</a>, if&nbsp;any</td></tr>
  239. * <tr><td valign="top" headers="construct bounds"><tt>\z</tt></td>
  240. * <td headers="matches">The end of the input</td></tr>
  241. *
  242. * <tr><th>&nbsp;</th></tr>
  243. * <tr align="left"><th colspan="2" id="greedy">Greedy quantifiers</th></tr>
  244. *
  245. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>?</tt></td>
  246. * <td headers="matches"><i>X</i>, once or not at all</td></tr>
  247. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>*</tt></td>
  248. * <td headers="matches"><i>X</i>, zero or more times</td></tr>
  249. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>+</tt></td>
  250. * <td headers="matches"><i>X</i>, one or more times</td></tr>
  251. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>}</tt></td>
  252. * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
  253. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,}</tt></td>
  254. * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
  255. * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}</tt></td>
  256. * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
  257. *
  258. * <tr><th>&nbsp;</th></tr>
  259. * <tr align="left"><th colspan="2" id="reluc">Reluctant quantifiers</th></tr>
  260. *
  261. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>??</tt></td>
  262. * <td headers="matches"><i>X</i>, once or not at all</td></tr>
  263. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>*?</tt></td>
  264. * <td headers="matches"><i>X</i>, zero or more times</td></tr>
  265. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>+?</tt></td>
  266. * <td headers="matches"><i>X</i>, one or more times</td></tr>
  267. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>}?</tt></td>
  268. * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
  269. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,}?</tt></td>
  270. * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
  271. * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}?</tt></td>
  272. * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
  273. *
  274. * <tr><th>&nbsp;</th></tr>
  275. * <tr align="left"><th colspan="2" id="poss">Possessive quantifiers</th></tr>
  276. *
  277. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>?+</tt></td>
  278. * <td headers="matches"><i>X</i>, once or not at all</td></tr>
  279. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>*+</tt></td>
  280. * <td headers="matches"><i>X</i>, zero or more times</td></tr>
  281. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>++</tt></td>
  282. * <td headers="matches"><i>X</i>, one or more times</td></tr>
  283. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>}+</tt></td>
  284. * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
  285. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,}+</tt></td>
  286. * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
  287. * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}+</tt></td>
  288. * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
  289. *
  290. * <tr><th>&nbsp;</th></tr>
  291. * <tr align="left"><th colspan="2" id="logical">Logical operators</th></tr>
  292. *
  293. * <tr><td valign="top" headers="construct logical"><i>XY</i></td>
  294. * <td headers="matches"><i>X</i> followed by <i>Y</i></td></tr>
  295. * <tr><td valign="top" headers="construct logical"><i>X</i><tt>|</tt><i>Y</i></td>
  296. * <td headers="matches">Either <i>X</i> or <i>Y</i></td></tr>
  297. * <tr><td valign="top" headers="construct logical"><tt>(</tt><i>X</i><tt>)</tt></td>
  298. * <td headers="matches">X, as a <a href="#cg">capturing group</a></td></tr>
  299. *
  300. * <tr><th>&nbsp;</th></tr>
  301. * <tr align="left"><th colspan="2" id="backref">Back references</th></tr>
  302. *
  303. * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>n</i></td>
  304. * <td valign="bottom" headers="matches">Whatever the <i>n</i><sup>th</sup>
  305. * <a href="#cg">capturing group</a> matched</td></tr>
  306. *
  307. * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>k</i>&lt;<i>name</i>&gt;</td>
  308. * <td valign="bottom" headers="matches">Whatever the
  309. * <a href="#groupname">named-capturing group</a> "name" matched</td></tr>
  310. *
  311. * <tr><th>&nbsp;</th></tr>
  312. * <tr align="left"><th colspan="2" id="quot">Quotation</th></tr>
  313. *
  314. * <tr><td valign="top" headers="construct quot"><tt>\</tt></td>
  315. * <td headers="matches">Nothing, but quotes the following character</td></tr>
  316. * <tr><td valign="top" headers="construct quot"><tt>\Q</tt></td>
  317. * <td headers="matches">Nothing, but quotes all characters until <tt>\E</tt></td></tr>
  318. * <tr><td valign="top" headers="construct quot"><tt>\E</tt></td>
  319. * <td headers="matches">Nothing, but ends quoting started by <tt>\Q</tt></td></tr>
  320. * <!-- Metachars: !$()*+.<>?[\]^{|} -->
  321. *
  322. * <tr><th>&nbsp;</th></tr>
  323. * <tr align="left"><th colspan="2" id="special">Special constructs (named-capturing and non-capturing)</th></tr>
  324. *
  325. * <tr><td valign="top" headers="construct special"><tt>(?&lt;<a href="#groupname">name</a>&gt;</tt><i>X</i><tt>)</tt></td>
  326. * <td headers="matches"><i>X</i>, as a named-capturing group</td></tr>
  327. * <tr><td valign="top" headers="construct special"><tt>(?:</tt><i>X</i><tt>)</tt></td>
  328. * <td headers="matches"><i>X</i>, as a non-capturing group</td></tr>
  329. * <tr><td valign="top" headers="construct special"><tt>(?idmsuxU-idmsuxU)&nbsp;</tt></td>
  330. * <td headers="matches">Nothing, but turns match flags <a href="#CASE_INSENSITIVE">i</a>
  331. * <a href="#UNIX_LINES">d</a> <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a>
  332. * <a href="#UNICODE_CASE">u</a> <a href="#COMMENTS">x</a> <a href="#UNICODE_CHARACTER_CLASS">U</a>
  333. * on - off</td></tr>
  334. * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux:</tt><i>X</i><tt>)</tt>&nbsp;&nbsp;</td>
  335. * <td headers="matches"><i>X</i>, as a <a href="#cg">non-capturing group</a> with the
  336. * given flags <a href="#CASE_INSENSITIVE">i</a> <a href="#UNIX_LINES">d</a>
  337. * <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a> <a href="#UNICODE_CASE">u</a >
  338. * <a href="#COMMENTS">x</a> on - off</td></tr>
  339. * <tr><td valign="top" headers="construct special"><tt>(?=</tt><i>X</i><tt>)</tt></td>
  340. * <td headers="matches"><i>X</i>, via zero-width positive lookahead</td></tr>
  341. * <tr><td valign="top" headers="construct special"><tt>(?!</tt><i>X</i><tt>)</tt></td>
  342. * <td headers="matches"><i>X</i>, via zero-width negative lookahead</td></tr>
  343. * <tr><td valign="top" headers="construct special"><tt>(?&lt;=</tt><i>X</i><tt>)</tt></td>
  344. * <td headers="matches"><i>X</i>, via zero-width positive lookbehind</td></tr>
  345. * <tr><td valign="top" headers="construct special"><tt>(?&lt;!</tt><i>X</i><tt>)</tt></td>
  346. * <td headers="matches"><i>X</i>, via zero-width negative lookbehind</td></tr>
  347. * <tr><td valign="top" headers="construct special"><tt>(?&gt;</tt><i>X</i><tt>)</tt></td>
  348. * <td headers="matches"><i>X</i>, as an independent, non-capturing group</td></tr>
  349. *
  350. * </table>
  351. *
  352. * <hr>
  353. *
  354. *
  355. * <a name="bs">
  356. * <h4> Backslashes, escapes, and quoting </h4>
  357. *
  358. * <p> The backslash character (<tt>'\'</tt>) serves to introduce escaped
  359. * constructs, as defined in the table above, as well as to quote characters
  360. * that otherwise would be interpreted as unescaped constructs. Thus the
  361. * expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a
  362. * left brace.
  363. *
  364. * <p> It is an error to use a backslash prior to any alphabetic character that
  365. * does not denote an escaped construct; these are reserved for future
  366. * extensions to the regular-expression language. A backslash may be used
  367. * prior to a non-alphabetic character regardless of whether that character is
  368. * part of an unescaped construct.
  369. *
  370. * <p> Backslashes within string literals in Java source code are interpreted
  371. * as required by
  372. * <cite>The Java&trade; Language Specification</cite>
  373. * as either Unicode escapes (section 3.3) or other character escapes (section 3.10.6)
  374. * It is therefore necessary to double backslashes in string
  375. * literals that represent regular expressions to protect them from
  376. * interpretation by the Java bytecode compiler. The string literal
  377. * <tt>"&#92;b"</tt>, for example, matches a single backspace character when
  378. * interpreted as a regular expression, while <tt>"&#92;&#92;b"</tt> matches a
  379. * word boundary. The string literal <tt>"&#92;(hello&#92;)"</tt> is illegal
  380. * and leads to a compile-time error; in order to match the string
  381. * <tt>(hello)</tt> the string literal <tt>"&#92;&#92;(hello&#92;&#92;)"</tt>
  382. * must be used.
  383. *
  384. * <a name="cc">
  385. * <h4> Character Classes </h4>
  386. *
  387. * <p> Character classes may appear within other character classes, and
  388. * may be composed by the union operator (implicit) and the intersection
  389. * operator (<tt>&amp;&amp;</tt>).
  390. * The union operator denotes a class that contains every character that is
  391. * in at least one of its operand classes. The intersection operator
  392. * denotes a class that contains every character that is in both of its
  393. * operand classes.
  394. *
  395. * <p> The precedence of character-class operators is as follows, from
  396. * highest to lowest:
  397. *
  398. * <blockquote><table border="0" cellpadding="1" cellspacing="0"
  399. * summary="Precedence of character class operators.">
  400. * <tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th>
  401. * <td>Literal escape&nbsp;&nbsp;&nbsp;&nbsp;</td>
  402. * <td><tt>\x</tt></td></tr>
  403. * <tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th>
  404. * <td>Grouping</td>
  405. * <td><tt>[...]</tt></td></tr>
  406. * <tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th>
  407. * <td>Range</td>
  408. * <td><tt>a-z</tt></td></tr>
  409. * <tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th>
  410. * <td>Union</td>
  411. * <td><tt>[a-e][i-u]</tt></td></tr>
  412. * <tr><th>5&nbsp;&nbsp;&nbsp;&nbsp;</th>
  413. * <td>Intersection</td>
  414. * <td><tt>[a-z&&[aeiou]]</tt></td></tr>
  415. * </table></blockquote>
  416. *
  417. * <p> Note that a different set of metacharacters are in effect inside
  418. * a character class than outside a character class. For instance, the
  419. * regular expression <tt>.</tt> loses its special meaning inside a
  420. * character class, while the expression <tt>-</tt> becomes a range
  421. * forming metacharacter.
  422. *
  423. * <a name="lt">
  424. * <h4> Line terminators </h4>
  425. *
  426. * <p> A <i>line terminator</i> is a one- or two-character sequence that marks
  427. * the end of a line of the input character sequence. The following are
  428. * recognized as line terminators:
  429. *
  430. * <ul>
  431. *
  432. * <li> A newline (line feed) character&nbsp;(<tt>'\n'</tt>),
  433. *
  434. * <li> A carriage-return character followed immediately by a newline
  435. * character&nbsp;(<tt>"\r\n"</tt>),
  436. *
  437. * <li> A standalone carriage-return character&nbsp;(<tt>'\r'</tt>),
  438. *
  439. * <li> A next-line character&nbsp;(<tt>'&#92;u0085'</tt>),
  440. *
  441. * <li> A line-separator character&nbsp;(<tt>'&#92;u2028'</tt>), or
  442. *
  443. * <li> A paragraph-separator character&nbsp;(<tt>'&#92;u2029</tt>).
  444. *
  445. * </ul>
  446. * <p>If {@link #UNIX_LINES} mode is activated, then the only line terminators
  447. * recognized are newline characters.
  448. *
  449. * <p> The regular expression <tt>.</tt> matches any character except a line
  450. * terminator unless the {@link #DOTALL} flag is specified.
  451. *
  452. * <p> By default, the regular expressions <tt>^</tt> and <tt>$</tt> ignore
  453. * line terminators and only match at the beginning and the end, respectively,
  454. * of the entire input sequence. If {@link #MULTILINE} mode is activated then
  455. * <tt>^</tt> matches at the beginning of input and after any line terminator
  456. * except at the end of input. When in {@link #MULTILINE} mode <tt>$</tt>
  457. * matches just before a line terminator or the end of the input sequence.
  458. *
  459. * <a name="cg">
  460. * <h4> Groups and capturing </h4>
  461. *
  462. * <a name="gnumber">
  463. * <h5> Group number </h5>
  464. * <p> Capturing groups are numbered by counting their opening parentheses from
  465. * left to right. In the expression <tt>((A)(B(C)))</tt>, for example, there
  466. * are four such groups: </p>
  467. *
  468. * <blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings">
  469. * <tr><th>1&nbsp;&nbsp;&nbsp;&nbsp;</th>
  470. * <td><tt>((A)(B(C)))</tt></td></tr>
  471. * <tr><th>2&nbsp;&nbsp;&nbsp;&nbsp;</th>
  472. * <td><tt>(A)</tt></td></tr>
  473. * <tr><th>3&nbsp;&nbsp;&nbsp;&nbsp;</th>
  474. * <td><tt>(B(C))</tt></td></tr>
  475. * <tr><th>4&nbsp;&nbsp;&nbsp;&nbsp;</th>
  476. * <td><tt>(C)</tt></td></tr>
  477. * </table></blockquote>
  478. *
  479. * <p> Group zero always stands for the entire expression.
  480. *
  481. * <p> Capturing groups are so named because, during a match, each subsequence
  482. * of the input sequence that matches such a group is saved. The captured
  483. * subsequence may be used later in the expression, via a back reference, and
  484. * may also be retrieved from the matcher once the match operation is complete.
  485. *
  486. * <a name="groupname">
  487. * <h5> Group name </h5>
  488. * <p>A capturing group can also be assigned a "name", a <tt>named-capturing group</tt>,
  489. * and then be back-referenced later by the "name". Group names are composed of
  490. * the following characters. The first character must be a <tt>letter</tt>.
  491. *
  492. * <ul>
  493. * <li> The uppercase letters <tt>'A'</tt> through <tt>'Z'</tt>
  494. * (<tt>'&#92;u0041'</tt>&nbsp;through&nbsp;<tt>'&#92;u005a'</tt>),
  495. * <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt>
  496. * (<tt>'&#92;u0061'</tt>&nbsp;through&nbsp;<tt>'&#92;u007a'</tt>),
  497. * <li> The digits <tt>'0'</tt> through <tt>'9'</tt>
  498. * (<tt>'&#92;u0030'</tt>&nbsp;through&nbsp;<tt>'&#92;u0039'</tt>),
  499. * </ul>
  500. *
  501. * <p> A <tt>named-capturing group</tt> is still numbered as described in
  502. * <a href="#gnumber">Group number</a>.
  503. *
  504. * <p> The captured input associated with a group is always the subsequence
  505. * that the group most recently matched. If a group is evaluated a second time
  506. * because of quantification then its previously-captured value, if any, will
  507. * be retained if the second evaluation fails. Matching the string
  508. * <tt>"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves
  509. * group two set to <tt>"b"</tt>. All captured input is discarded at the
  510. * beginning of each match.
  511. *
  512. * <p> Groups beginning with <tt>(?</tt> are either pure, <i>non-capturing</i> groups
  513. * that do not capture text and do not count towards the group total, or
  514. * <i>named-capturing</i> group.
  515. *
  516. * <h4> Unicode support </h4>
  517. *
  518. * <p> This class is in conformance with Level 1 of <a
  519. * href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
  520. * Standard #18: Unicode Regular Expression</i></a>, plus RL2.1
  521. * Canonical Equivalents.
  522. * <p>
  523. * <b>Unicode escape sequences</b> such as <tt>&#92;u2014</tt> in Java source code
  524. * are processed as described in section 3.3 of
  525. * <cite>The Java&trade; Language Specification</cite>.
  526. * Such escape sequences are also implemented directly by the regular-expression
  527. * parser so that Unicode escapes can be used in expressions that are read from
  528. * files or from the keyboard. Thus the strings <tt>"&#92;u2014"</tt> and
  529. * <tt>"\\u2014"</tt>, while not equal, compile into the same pattern, which
  530. * matches the character with hexadecimal value <tt>0x2014</tt>.
  531. * <p>
  532. * A Unicode character can also be represented in a regular-expression by
  533. * using its <b>Hex notation</b>(hexadecimal code point value) directly as described in construct
  534. * <tt>&#92;x{...}</tt>, for example a supplementary character U+2011F
  535. * can be specified as <tt>&#92;x{2011F}</tt>, instead of two consecutive
  536. * Unicode escape sequences of the surrogate pair
  537. * <tt>&#92;uD840</tt><tt>&#92;uDD1F</tt>.
  538. * <p>
  539. * Unicode scripts, blocks, categories and binary properties are written with
  540. * the <tt>\p</tt> and <tt>\P</tt> constructs as in Perl.
  541. * <tt>\p{</tt><i>prop</i><tt>}</tt> matches if
  542. * the input has the property <i>prop</i>, while <tt>\P{</tt><i>prop</i><tt>}</tt>
  543. * does not match if the input has that property.
  544. * <p>
  545. * Scripts, blocks, categories and binary properties can be used both inside
  546. * and outside of a character class.
  547. * <a name="usc">
  548. * <p>
  549. * <b>Scripts</b> are specified either with the prefix {@code Is}, as in
  550. * {@code IsHiragana}, or by using the {@code script} keyword (or its short
  551. * form {@code sc})as in {@code script=Hiragana} or {@code sc=Hiragana}.
  552. * <p>
  553. * The script names supported by <code>Pattern</code> are the valid script names
  554. * accepted and defined by
  555. * {@link java.lang.Character.UnicodeScript#forName(String) UnicodeScript.forName}.
  556. * <a name="ubc">
  557. * <p>
  558. * <b>Blocks</b> are specified with the prefix {@code In}, as in
  559. * {@code InMongolian}, or by using the keyword {@code block} (or its short
  560. * form {@code blk}) as in {@code block=Mongolian} or {@code blk=Mongolian}.
  561. * <p>
  562. * The block names supported by <code>Pattern</code> are the valid block names
  563. * accepted and defined by
  564. * {@link java.lang.Character.UnicodeBlock#forName(String) UnicodeBlock.forName}.
  565. * <p>
  566. * <a name="ucc">
  567. * <b>Categories</b> may be specified with the optional prefix {@code Is}:
  568. * Both {@code \p{L}} and {@code \p{IsL}} denote the category of Unicode
  569. * letters. Same as scripts and blocks, categories can also be specified
  570. * by using the keyword {@code general_category} (or its short form
  571. * {@code gc}) as in {@code general_category=Lu} or {@code gc=Lu}.
  572. * <p>
  573. * The supported categories are those of
  574. * <a href="http://www.unicode.org/unicode/standard/standard.html">
  575. * <i>The Unicode Standard</i></a> in the version specified by the
  576. * {@link java.lang.Character Character} class. The category names are those
  577. * defined in the Standard, both normative and informative.
  578. * <p>
  579. * <a name="ubpc">
  580. * <b>Binary properties</b> are specified with the prefix {@code Is}, as in
  581. * {@code IsAlphabetic}. The supported binary properties by <code>Pattern</code>
  582. * are
  583. * <ul>
  584. * <li> Alphabetic
  585. * <li> Ideographic
  586. * <li> Letter
  587. * <li> Lowercase
  588. * <li> Uppercase
  589. * <li> Titlecase
  590. * <li> Punctuation
  591. * <Li> Control
  592. * <li> White_Space
  593. * <li> Digit
  594. * <li> Hex_Digit
  595. * <li> Noncharacter_Code_Point
  596. * <li> Assigned
  597. * </ul>
  598. * <p>
  599. * <b>Predefined Character classes</b> and <b>POSIX character classes</b> are in
  600. * conformance with the recommendation of <i>Annex C: Compatibility Properties</i>
  601. * of <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Regular Expression
  602. * </i></a>, when {@link #UNICODE_CHARACTER_CLASS} flag is specified.
  603. * <p>
  604. * <table border="0" cellpadding="1" cellspacing="0"
  605. * summary="predefined and posix character classes in Unicode mode">
  606. * <tr align="left">
  607. * <th bgcolor="#CCCCFF" align="left" id="classes">Classes</th>
  608. * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th>
  609. *</tr>
  610. * <tr><td><tt>\p{Lower}</tt></td>
  611. * <td>A lowercase character:<tt>\p{IsLowercase}</tt></td></tr>
  612. * <tr><td><tt>\p{Upper}</tt></td>
  613. * <td>An uppercase character:<tt>\p{IsUppercase}</tt></td></tr>
  614. * <tr><td><tt>\p{ASCII}</tt></td>
  615. * <td>All ASCII:<tt>[\x00-\x7F]</tt></td></tr>
  616. * <tr><td><tt>\p{Alpha}</tt></td>
  617. * <td>An alphabetic character:<tt>\p{IsAlphabetic}</tt></td></tr>
  618. * <tr><td><tt>\p{Digit}</tt></td>
  619. * <td>A decimal digit character:<tt>p{IsDigit}</tt></td></tr>
  620. * <tr><td><tt>\p{Alnum}</tt></td>
  621. * <td>An alphanumeric character:<tt>[\p{IsAlphabetic}\p{IsDigit}]</tt></td></tr>
  622. * <tr><td><tt>\p{Punct}</tt></td>
  623. * <td>A punctuation character:<tt>p{IsPunctuation}</tt></td></tr>
  624. * <tr><td><tt>\p{Graph}</tt></td>
  625. * <td>A visible character: <tt>[^\p{IsWhite_Space}\p{gc=Cc}\p{gc=Cs}\p{gc=Cn}]</tt></td></tr>
  626. * <tr><td><tt>\p{Print}</tt></td>
  627. * <td>A printable character: <tt>[\p{Graph}\p{Blank}&&[^\p{Cntrl}]]</tt></td></tr>
  628. * <tr><td><tt>\p{Blank}</tt></td>
  629. * <td>A space or a tab: <tt>[\p{IsWhite_Space}&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]]</tt></td></tr>
  630. * <tr><td><tt>\p{Cntrl}</tt></td>
  631. * <td>A control character: <tt>\p{gc=Cc}</tt></td></tr>
  632. * <tr><td><tt>\p{XDigit}</tt></td>
  633. * <td>A hexadecimal digit: <tt>[\p{gc=Nd}\p{IsHex_Digit}]</tt></td></tr>
  634. * <tr><td><tt>\p{Space}</tt></td>
  635. * <td>A whitespace character:<tt>\p{IsWhite_Space}</tt></td></tr>
  636. * <tr><td><tt>\d</tt></td>
  637. * <td>A digit: <tt>\p{IsDigit}</tt></td></tr>
  638. * <tr><td><tt>\D</tt></td>
  639. * <td>A non-digit: <tt>[^\d]</tt></td></tr>
  640. * <tr><td><tt>\s</tt></td>
  641. * <td>A whitespace character: <tt>\p{IsWhite_Space}</tt></td></tr>
  642. * <tr><td><tt>\S</tt></td>
  643. * <td>A non-whitespace character: <tt>[^\s]</tt></td></tr>
  644. * <tr><td><tt>\w</tt></td>
  645. * <td>A word character: <tt>[\p{Alpha}\p{gc=Mn}\p{gc=Me}\p{gc=Mc}\p{Digit}\p{gc=Pc}]</tt></td></tr>
  646. * <tr><td><tt>\W</tt></td>
  647. * <td>A non-word character: <tt>[^\w]</tt></td></tr>
  648. * </table>
  649. * <p>
  650. * <a name="jcc">
  651. * Categories that behave like the java.lang.Character
  652. * boolean is<i>methodname</i> methods (except for the deprecated ones) are
  653. * available through the same <tt>\p{</tt><i>prop</i><tt>}</tt> syntax where
  654. * the specified property has the name <tt>java<i>methodname</i></tt>.
  655. *
  656. * <h4> Comparison to Perl 5 </h4>
  657. *
  658. * <p>The <code>Pattern</code> engine performs traditional NFA-based matching
  659. * with ordered alternation as occurs in Perl 5.
  660. *
  661. * <p> Perl constructs not supported by this class: </p>
  662. *
  663. * <ul>
  664. * <li><p> Predefined character classes (Unicode character)
  665. * <p><tt>\h&nbsp;&nbsp;&nbsp;&nbsp;</tt>A horizontal whitespace
  666. * <p><tt>\H&nbsp;&nbsp;&nbsp;&nbsp;</tt>A non horizontal whitespace
  667. * <p><tt>\v&nbsp;&nbsp;&nbsp;&nbsp;</tt>A vertical whitespace
  668. * <p><tt>\V&nbsp;&nbsp;&nbsp;&nbsp;</tt>A non vertical whitespace
  669. * <p><tt>\R&nbsp;&nbsp;&nbsp;&nbsp;</tt>Any Unicode linebreak sequence
  670. * <tt>\u005cu000D\u005cu000A|[\u005cu000A\u005cu000B\u005cu000C\u005cu000D\u005cu0085\u005cu2028\u005cu2029]</tt>
  671. * <p><tt>\X&nbsp;&nbsp;&nbsp;&nbsp;</tt>Match Unicode
  672. * <a href="http://www.unicode.org/reports/tr18/#Default_Grapheme_Clusters">
  673. * <i>extended grapheme cluster</i></a>
  674. * </p></li>
  675. *
  676. * <li><p> The backreference constructs, <tt>\g{</tt><i>n</i><tt>}</tt> for
  677. * the <i>n</i><sup>th</sup><a href="#cg">capturing group</a> and
  678. * <tt>\g{</tt><i>name</i><tt>}</tt> for
  679. * <a href="#groupname">named-capturing group</a>.
  680. * </p></li>
  681. *
  682. * <li><p> The named character construct, <tt>\N{</tt><i>name</i><tt>}</tt>
  683. * for a Unicode character by its name.
  684. * </p></li>
  685. *
  686. * <li><p> The conditional constructs
  687. * <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>)</tt> and
  688. * <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>,
  689. * </p></li>
  690. *
  691. * <li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt>
  692. * and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li>
  693. *
  694. * <li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li>
  695. *
  696. * <li><p> The preprocessing operations <tt>\l</tt> <tt>&#92;u</tt>,
  697. * <tt>\L</tt>, and <tt>\U</tt>. </p></li>
  698. *
  699. * </ul>
  700. *
  701. * <p> Constructs supported by this class but not by Perl: </p>
  702. *
  703. * <ul>
  704. *
  705. * <li><p> Character-class union and intersection as described
  706. * <a href="#cc">above</a>.</p></li>
  707. *
  708. * </ul>
  709. *
  710. * <p> Notable differences from Perl: </p>
  711. *
  712. * <ul>
  713. *
  714. * <li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted
  715. * as back references; a backslash-escaped number greater than <tt>9</tt> is
  716. * treated as a back reference if at least that many subexpressions exist,
  717. * otherwise it is interpreted, if possible, as an octal escape. In this
  718. * class octal escapes must always begin with a zero. In this class,
  719. * <tt>\1</tt> through <tt>\9</tt> are always interpreted as back
  720. * references, and a larger number is accepted as a back reference if at
  721. * least that many subexpressions exist at that point in the regular
  722. * expression, otherwise the parser will drop digits until the number is
  723. * smaller or equal to the existing number of groups or it is one digit.
  724. * </p></li>
  725. *
  726. * <li><p> Perl uses the <tt>g</tt> flag to request a match that resumes
  727. * where the last match left off. This functionality is provided implicitly
  728. * by the {@link Matcher} class: Repeated invocations of the {@link
  729. * Matcher#find find} method will resume where the last match left off,
  730. * unless the matcher is reset. </p></li>
  731. *
  732. * <li><p> In Perl, embedded flags at the top level of an expression affect
  733. * the whole expression. In this class, embedded flags always take effect
  734. * at the point at which they appear, whether they are at the top level or
  735. * within a group; in the latter case, flags are restored at the end of the
  736. * group just as in Perl. </p></li>
  737. *
  738. * </ul>
  739. *
  740. *
  741. * <p> For a more precise description of the behavior of regular expression
  742. * constructs, please see <a href="http://www.oreilly.com/catalog/regex3/">
  743. * <i>Mastering Regular Expressions, 3nd Edition</i>, Jeffrey E. F. Friedl,
  744. * O'Reilly and Associates, 2006.</a>
  745. * </p>
  746. *
  747. * @see java.lang.String#split(String, int)
  748. * @see java.lang.String#split(String)
  749. *
  750. * @author Mike McCloskey
  751. * @author Mark Reinhold
  752. * @author JSR-51 Expert Group
  753. * @since 1.4
  754. * @spec JSR-51
  755. */
  756. public final class Pattern
  757. implements java.io.Serializable
  758. {
  759. /**
  760. * Regular expression modifier values. Instead of being passed as
  761. * arguments, they can also be passed as inline modifiers.
  762. * For example, the following statements have the same effect.
  763. * <pre>
  764. * RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M);
  765. * RegExp r2 = RegExp.compile("(?im)abc", 0);
  766. * </pre>
  767. *
  768. * The flags are duplicated so that the familiar Perl match flag
  769. * names are available.
  770. */
  771. /**
  772. * Enables Unix lines mode.
  773. *
  774. * <p> In this mode, only the <tt>'\n'</tt> line terminator is recognized
  775. * in the behavior of <tt>.</tt>, <tt>^</tt>, and <tt>$</tt>.
  776. *
  777. * <p> Unix lines mode can also be enabled via the embedded flag
  778. * expression&nbsp;<tt>(?d)</tt>.
  779. */
  780. public static final int UNIX_LINES = 0x01;
  781. /**
  782. * Enables case-insensitive matching.
  783. *
  784. * <p> By default, case-insensitive matching assumes that only characters
  785. * in the US-ASCII charset are being matched. Unicode-aware
  786. * case-insensitive matching can be enabled by specifying the {@link
  787. * #UNICODE_CASE} flag in conjunction with this flag.
  788. *
  789. * <p> Case-insensitive matching can also be enabled via the embedded flag
  790. * expression&nbsp;<tt>(?i)</tt>.
  791. *
  792. * <p> Specifying this flag may impose a slight performance penalty. </p>
  793. */
  794. public static final int CASE_INSENSITIVE = 0x02;
  795. /**
  796. * Permits whitespace and comments in pattern.
  797. *
  798. * <p> In this mode, whitespace is ignored, and embedded comments starting
  799. * with <tt>#</tt> are ignored until the end of a line.
  800. *
  801. * <p> Comments mode can also be enabled via the embedded flag
  802. * expression&nbsp;<tt>(?x)</tt>.
  803. */
  804. public static final int COMMENTS = 0x04;
  805. /**
  806. * Enables multiline mode.
  807. *
  808. * <p> In multiline mode the expressions <tt>^</tt> and <tt>$</tt> match
  809. * just after or just before, respectively, a line terminator or the end of
  810. * the input sequence. By default these expressions only match at the
  811. * beginning and the end of the entire input sequence.
  812. *
  813. * <p> Multiline mode can also be enabled via the embedded flag
  814. * expression&nbsp;<tt>(?m)</tt>. </p>
  815. */
  816. public static final int MULTILINE = 0x08;
  817. /**
  818. * Enables literal parsing of the pattern.
  819. *
  820. * <p> When this flag is specified then the input string that specifies
  821. * the pattern is treated as a sequence of literal characters.
  822. * Metacharacters or escape sequences in the input sequence will be
  823. * given no special meaning.
  824. *
  825. * <p>The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact on
  826. * matching when used in conjunction with this flag. The other flags
  827. * become superfluous.
  828. *
  829. * <p> There is no embedded flag character for enabling literal parsing.
  830. * @since 1.5
  831. */
  832. public static final int LITERAL = 0x10;
  833. /**
  834. * Enables dotall mode.
  835. *
  836. * <p> In dotall mode, the expression <tt>.</tt> matches any character,
  837. * including a line terminator. By default this expression does not match
  838. * line terminators.
  839. *
  840. * <p> Dotall mode can also be enabled via the embedded flag
  841. * expression&nbsp;<tt>(?s)</tt>. (The <tt>s</tt> is a mnemonic for
  842. * "single-line" mode, which is what this is called in Perl.) </p>
  843. */
  844. public static final int DOTALL = 0x20;
  845. /**
  846. * Enables Unicode-aware case folding.
  847. *
  848. * <p> When this flag is specified then case-insensitive matching, when
  849. * enabled by the {@link #CASE_INSENSITIVE} flag, is done in a manner
  850. * consistent with the Unicode Standard. By default, case-insensitive
  851. * matching assumes that only characters in the US-ASCII charset are being
  852. * matched.
  853. *
  854. * <p> Unicode-aware case folding can also be enabled via the embedded flag
  855. * expression&nbsp;<tt>(?u)</tt>.
  856. *
  857. * <p> Specifying this flag may impose a performance penalty. </p>
  858. */
  859. public static final int UNICODE_CASE = 0x40;
  860. /**
  861. * Enables canonical equivalence.
  862. *
  863. * <p> When this flag is specified then two characters will be considered
  864. * to match if, and only if, their full canonical decompositions match.
  865. * The expression <tt>"a&#92;u030A"</tt>, for example, will match the
  866. * string <tt>"&#92;u00E5"</tt> when this flag is specified. By default,
  867. * matching does not take canonical equivalence into account.
  868. *
  869. * <p> There is no embedded flag character for enabling canonical
  870. * equivalence.
  871. *
  872. * <p> Specifying this flag may impose a performance penalty. </p>
  873. */
  874. public static final int CANON_EQ = 0x80;
  875. /**
  876. * Enables the Unicode version of <i>Predefined character classes</i> and
  877. * <i>POSIX character classes</i>.
  878. *
  879. * <p> When this flag is specified then the (US-ASCII only)
  880. * <i>Predefined character classes</i> and <i>POSIX character classes</i>
  881. * are in conformance with
  882. * <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
  883. * Standard #18: Unicode Regular Expression</i></a>
  884. * <i>Annex C: Compatibility Properties</i>.
  885. * <p>
  886. * The UNICODE_CHARACTER_CLASS mode can also be enabled via the embedded
  887. * flag expression&nbsp;<tt>(?U)</tt>.
  888. * <p>
  889. * The flag implies UNICODE_CASE, that is, it enables Unicode-aware case
  890. * folding.
  891. * <p>
  892. * Specifying this flag may impose a performance penalty. </p>
  893. * @since 1.7
  894. */
  895. public static final int UNICODE_CHARACTER_CLASS = 0x100;
  896. /* Pattern has only two serialized components: The pattern string
  897. * and the flags, which are all that is needed to recompile the pattern
  898. * when it is deserialized.
  899. */
  900. /** use serialVersionUID from Merlin b59 for interoperability */
  901. private static final long serialVersionUID = 5073258162644648461L;
  902. /**
  903. * The original regular-expression pattern string.
  904. *
  905. * @serial
  906. */
  907. private String pattern;
  908. /**
  909. * The original pattern flags.
  910. *
  911. * @serial
  912. */
  913. private int flags;
  914. /**
  915. * Boolean indicating this Pattern is compiled; this is necessary in order
  916. * to lazily compile deserialized Patterns.
  917. */
  918. private transient volatile boolean compiled = false;
  919. /**
  920. * The normalized pattern string.
  921. */
  922. private transient String normalizedPattern;
  923. /**
  924. * The starting point of state machine for the find operation. This allows
  925. * a match to start anywhere in the input.
  926. */
  927. transient Node root;
  928. /**
  929. * The root of object tree for a match operation. The pattern is matched
  930. * at the beginning. This may include a find that uses BnM or a First
  931. * node.
  932. */
  933. transient Node matchRoot;
  934. /**
  935. * Temporary storage used by parsing pattern slice.
  936. */
  937. transient int[] buffer;
  938. /**
  939. * Map the "name" of the "named capturing group" to its group id
  940. * node.
  941. */
  942. transient volatile Map<String, Integer> namedGroups;
  943. /**
  944. * Temporary storage used while parsing group references.
  945. */
  946. transient GroupHead[] groupNodes;
  947. /**
  948. * Temporary null terminated code point array used by pattern compiling.
  949. */
  950. private transient int[] temp;
  951. /**
  952. * The number of capturing groups in this Pattern. Used by matchers to
  953. * allocate storage needed to perform a match.
  954. */
  955. transient int capturingGroupCount;
  956. /**
  957. * The local variable count used by parsing tree. Used by matchers to
  958. * allocate storage needed to perform a match.
  959. */
  960. transient int localCount;
  961. /**
  962. * Index into the pattern string that keeps track of how much has been
  963. * parsed.
  964. */
  965. private transient int cursor;
  966. /**
  967. * Holds the length of the pattern string.
  968. */
  969. private transient int patternLength;
  970. /**
  971. * If the Start node might possibly match supplementary characters.
  972. * It is set to true during compiling if
  973. * (1) There is supplementary char in pattern, or
  974. * (2) There is complement node of Category or Block
  975. */
  976. private transient boolean hasSupplementary;
  977. /**
  978. * Compiles the given regular expression into a pattern. </p>
  979. *
  980. * @param regex
  981. * The expression to be compiled
  982. *
  983. * @throws PatternSyntaxException
  984. * If the expression's syntax is invalid
  985. */
  986. public static Pattern compile(String regex) {
  987. return new Pattern(regex, 0);
  988. }
  989. /**
  990. * Compiles the given regular expression into a pattern with the given
  991. * flags. </p>
  992. *
  993. * @param regex
  994. * The expression to be compiled
  995. *
  996. * @param flags
  997. * Match flags, a bit mask that may include
  998. * {@link #CASE_INSENSITIVE}, {@link #MULTILINE}, {@link #DOTALL},
  999. * {@link #UNICODE_CASE}, {@link #CANON_EQ}, {@link #UNIX_LINES},
  1000. * {@link #LITERAL}, {@link #UNICODE_CHARACTER_CLASS}
  1001. * and {@link #COMMENTS}
  1002. *
  1003. * @throws IllegalArgumentException
  1004. * If bit values other than those corresponding to the defined
  1005. * match flags are set in <tt>flags</tt>
  1006. *
  1007. * @throws PatternSyntaxException
  1008. * If the expression's syntax is invalid
  1009. */
  1010. public static Pattern compile(String regex, int flags) {
  1011. return new Pattern(regex, flags);
  1012. }
  1013. /**
  1014. * Returns the regular expression from which this pattern was compiled.
  1015. * </p>
  1016. *
  1017. * @return The source of this pattern
  1018. */
  1019. public String pattern() {
  1020. return pattern;
  1021. }
  1022. /**
  1023. * <p>Returns the string representation of this pattern. This
  1024. * is the regular expression from which this pattern was
  1025. * compiled.</p>
  1026. *
  1027. * @return The string representation of this pattern
  1028. * @since 1.5
  1029. */
  1030. public String toString() {
  1031. return pattern;
  1032. }
  1033. /**
  1034. * Creates a matcher that will match the given input against this pattern.
  1035. * </p>
  1036. *
  1037. * @param input
  1038. * The character sequence to be matched
  1039. *
  1040. * @return A new matcher for this pattern
  1041. */
  1042. public Matcher matcher(CharSequence input) {
  1043. if (!compiled) {
  1044. synchronized(this) {
  1045. if (!compiled)
  1046. compile();
  1047. }
  1048. }
  1049. Matcher m = new Matcher(this, input);
  1050. return m;
  1051. }
  1052. /**
  1053. * Returns this pattern's match flags. </p>
  1054. *
  1055. * @return The match flags specified when this pattern was compiled
  1056. */
  1057. public int flags() {
  1058. return flags;
  1059. }
  1060. /**
  1061. * Compiles the given regular expression and attempts to match the given
  1062. * input against it.
  1063. *
  1064. * <p> An invocation of this convenience method of the form
  1065. *
  1066. * <blockquote><pre>
  1067. * Pattern.matches(regex, input);</pre></blockquote>
  1068. *
  1069. * behaves in exactly the same way as the expression
  1070. *
  1071. * <blockquote><pre>
  1072. * Pattern.compile(regex).matcher(input).matches()</pre></blockquote>
  1073. *
  1074. * <p> If a pattern is to be used multiple times, compiling it once and reusing
  1075. * it will be more efficient than invoking this method each time. </p>
  1076. *
  1077. * @param regex
  1078. * The expression to be compiled
  1079. *
  1080. * @param input
  1081. * The character sequence to be matched
  1082. *
  1083. * @throws PatternSyntaxException
  1084. * If the expression's syntax is invalid
  1085. */
  1086. public static boolean matches(String regex, CharSequence input) {
  1087. Pattern p = Pattern.compile(regex);
  1088. Matcher m = p.matcher(input);
  1089. return m.matches();
  1090. }
  1091. /**
  1092. * Splits the given input sequence around matches of this pattern.
  1093. *
  1094. * <p> The array returned by this method contains each substring of the
  1095. * input sequence that is terminated by another subsequence that matches
  1096. * this pattern or is terminated by the end of the input sequence. The
  1097. * substrings in the array are in the order in which they occur in the
  1098. * input. If this pattern does not match any subsequence of the input then
  1099. * the resulting array has just one element, namely the input sequence in
  1100. * string form.
  1101. *
  1102. * <p> The <tt>limit</tt> parameter controls the number of times the
  1103. * pattern is applied and therefore affects the length of the resulting
  1104. * array. If the limit <i>n</i> is greater than zero then the pattern
  1105. * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
  1106. * length will be no greater than <i>n</i>, and the array's last entry
  1107. * will contain all input beyond the last matched delimiter. If <i>n</i>
  1108. * is non-positive then the pattern will be applied as many times as
  1109. * possible and the array can have any length. If <i>n</i> is zero then
  1110. * the pattern will be applied as many times as possible, the array can
  1111. * have any length, and trailing empty strings will be discarded.
  1112. *
  1113. * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
  1114. * results with these parameters:
  1115. *
  1116. * <blockquote><table cellpadding=1 cellspacing=0
  1117. * summary="Split examples showing regex, limit, and result">
  1118. * <tr><th><P align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
  1119. * <th><P align="left"><i>Limit&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
  1120. * <th><P align="left"><i>Result&nbsp;&nbsp;&nbsp;&nbsp;</i></th></tr>
  1121. * <tr><td align=center>:</td>
  1122. * <td align=center>2</td>
  1123. * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
  1124. * <tr><td align=center>:</td>
  1125. * <td align=center>5</td>
  1126. * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  1127. * <tr><td align=center>:</td>
  1128. * <td align=center>-2</td>
  1129. * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  1130. * <tr><td align=center>o</td>
  1131. * <td align=center>5</td>
  1132. * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
  1133. * <tr><td align=center>o</td>
  1134. * <td align=center>-2</td>
  1135. * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
  1136. * <tr><td align=center>o</td>
  1137. * <td align=center>0</td>
  1138. * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
  1139. * </table></blockquote>
  1140. *
  1141. *
  1142. * @param input
  1143. * The character sequence to be split
  1144. *
  1145. * @param limit
  1146. * The result threshold, as described above
  1147. *
  1148. * @return The array of strings computed by splitting the input
  1149. * around matches of this pattern
  1150. */
  1151. public String[] split(CharSequence input, int limit) {
  1152. int index = 0;
  1153. boolean matchLimited = limit > 0;
  1154. ArrayList<String> matchList = new ArrayList<>();
  1155. Matcher m = matcher(input);
  1156. // Add segments before each match found
  1157. while(m.find()) {
  1158. if (!matchLimited || matchList.size() < limit - 1) {
  1159. String match = input.subSequence(index, m.start()).toString();
  1160. matchList.add(match);
  1161. index = m.end();
  1162. } else if (matchList.size() == limit - 1) { // last one
  1163. String match = input.subSequence(index,
  1164. input.length()).toString();
  1165. matchList.add(match);
  1166. index = m.end();
  1167. }
  1168. }
  1169. // If no match was found, return this
  1170. if (index == 0)
  1171. return new String[] {input.toString()};
  1172. // Add remaining segment
  1173. if (!matchLimited || matchList.size() < limit)
  1174. matchList.add(input.subSequence(index, input.length()).toString());
  1175. // Construct result
  1176. int resultSize = matchList.size();
  1177. if (limit == 0)
  1178. while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
  1179. resultSize--;
  1180. String[] result = new String[resultSize];
  1181. return matchList.subList(0, resultSize).toArray(result);
  1182. }
  1183. /**
  1184. * Splits the given input sequence around matches of this pattern.
  1185. *
  1186. * <p> This method works as if by invoking the two-argument {@link
  1187. * #split(java.lang.CharSequence, int) split} method with the given input
  1188. * sequence and a limit argument of zero. Trailing empty strings are
  1189. * therefore not included in the resulting array. </p>
  1190. *
  1191. * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
  1192. * results with these expressions:
  1193. *
  1194. * <blockquote><table cellpadding=1 cellspacing=0
  1195. * summary="Split examples showing regex and result">
  1196. * <tr><th><P align="left"><i>Regex&nbsp;&nbsp;&nbsp;&nbsp;</i></th>
  1197. * <th><P align="left"><i>Result</i></th></tr>
  1198. * <tr><td align=center>:</td>
  1199. * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
  1200. * <tr><td align=center>o</td>
  1201. * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
  1202. * </table></blockquote>
  1203. *
  1204. *
  1205. * @param input
  1206. * The character sequence to be split
  1207. *
  1208. * @return The array of strings computed by splitting the input
  1209. * around matches of this pattern
  1210. */
  1211. public String[] split(CharSequence input) {
  1212. return split(input, 0);
  1213. }
  1214. /**
  1215. * Returns a literal pattern <code>String</code> for the specified
  1216. * <code>String</code>.
  1217. *
  1218. * <p>This method produces a <code>String</code> that can be used to
  1219. * create a <code>Pattern</code> that would match the string
  1220. * <code>s</code> as if it were a literal pattern.</p> Metacharacters
  1221. * or escape sequences in the input sequence will be given no special
  1222. * meaning.
  1223. *
  1224. * @param s The string to be literalized
  1225. * @return A literal string replacement
  1226. * @since 1.5
  1227. */
  1228. public static String quote(String s) {
  1229. int slashEIndex = s.indexOf("\\E");
  1230. if (slashEIndex == -1)
  1231. return "\\Q" + s + "\\E";
  1232. StringBuilder sb = new StringBuilder(s.length() * 2);
  1233. sb.append("\\Q");
  1234. slashEIndex = 0;
  1235. int current = 0;
  1236. while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
  1237. sb.append(s.substring(current, slashEIndex));
  1238. current = slashEIndex + 2;
  1239. sb.append("\\E\\\\E\\Q");
  1240. }
  1241. sb.append(s.substring(current, s.length()));
  1242. sb.append("\\E");
  1243. return sb.toString();
  1244. }
  1245. /**
  1246. * Recompile the Pattern instance from a stream. The original pattern
  1247. * string is read in and the object tree is recompiled from it.
  1248. */
  1249. private void readObject(java.io.ObjectInputStream s)
  1250. throws java.io.IOException, ClassNotFoundException {
  1251. // Read in all fields
  1252. s.defaultReadObject();
  1253. // Initialize counts
  1254. capturingGroupCount = 1;
  1255. localCount = 0;
  1256. // if length > 0, the Pattern is lazily compiled
  1257. compiled = false;
  1258. if (pattern.length() == 0) {
  1259. root = new Start(lastAccept);
  1260. matchRoot = lastAccept;
  1261. compiled = true;
  1262. }
  1263. }
  1264. /**
  1265. * This private constructor is used to create all Patterns. The pattern
  1266. * string and match flags are all that is needed to completely describe
  1267. * a Pattern. An empty pattern string results in an object tree with
  1268. * only a Start node and a LastNode node.
  1269. */
  1270. private Pattern(String p, int f) {
  1271. pattern = p;
  1272. flags = f;
  1273. // to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
  1274. if ((flags & UNICODE_CHARACTER_CLASS) != 0)
  1275. flags |= UNICODE_CASE;
  1276. // Reset group index count
  1277. capturingGroupCount = 1;
  1278. localCount = 0;
  1279. if (pattern.length() > 0) {
  1280. compile();
  1281. } else {
  1282. root = new Start(lastAccept);
  1283. matchRoot = lastAccept;
  1284. }
  1285. }
  1286. /**
  1287. * The pattern is converted to normalizedD form and then a pure group
  1288. * is constructed to match canonical equivalences of the characters.
  1289. */
  1290. private void normalize() {
  1291. boolean inCharClass = false;
  1292. int lastCodePoint = -1;
  1293. // Convert pattern into normalizedD form
  1294. normalizedPattern = Normalizer.normalize(pattern, Normalizer.Form.NFD);
  1295. patternLength = normalizedPattern.length();
  1296. // Modify pattern to match canonical equivalences
  1297. StringBuilder newPattern = new StringBuilder(patternLength);
  1298. for(int i=0; i<patternLength; ) {
  1299. int c = normalizedPattern.codePointAt(i);
  1300. StringBuilder sequenceBuffer;
  1301. if ((Character.getType(c) == Character.NON_SPACING_MARK)
  1302. && (lastCodePoint != -1)) {
  1303. sequenceBuffer = new StringBuilder();
  1304. sequenceBuffer.appendCodePoint(lastCodePoint);
  1305. sequenceBuffer.appendCodePoint(c);
  1306. while(Character.getType(c) == Character.NON_SPACING_MARK) {
  1307. i += Character.charCount(c);
  1308. if (i >= patternLength)
  1309. break;
  1310. c = normalizedPattern.codePointAt(i);
  1311. sequenceBuffer.appendCodePoint(c);
  1312. }
  1313. String ea = produceEquivalentAlternation(
  1314. sequenceBuffer.toString());
  1315. newPattern.setLength(newPattern.length()-Character.charCount(lastCodePoint));
  1316. newPattern.append("(?:").append(ea).append(")");
  1317. } else if (c == '[' && lastCodePoint != '\\') {
  1318. i = normalizeCharClass(newPattern, i);
  1319. } else {
  1320. newPattern.appendCodePoint(c);
  1321. }
  1322. lastCodePoint = c;
  1323. i += Character.charCount(c);
  1324. }
  1325. normalizedPattern = newPattern.toString();
  1326. }
  1327. /**
  1328. * Complete the character class being parsed and add a set
  1329. * of alternations to it that will match the canonical equivalences
  1330. * of the characters within the class.
  1331. */
  1332. private int normalizeCharClass(StringBuilder newPattern, int i) {
  1333. StringBuilder charClass = new StringBuilder();
  1334. StringBuilder eq = null;
  1335. int lastCodePoint = -1;
  1336. String result;
  1337. i++;
  1338. charClass.append("[");
  1339. while(true) {
  1340. int c = normalizedPattern.codePointAt(i);
  1341. StringBuilder sequenceBuffer;
  1342. if (c == ']' && lastCodePoint != '\\') {
  1343. charClass.append((char)c);
  1344. break;
  1345. } else if (Character.getType(c) == Character.NON_SPACING_MARK) {
  1346. sequenceBuffer = new StringBuilder();
  1347. sequenceBuffer.appendCodePoint(lastCodePoint);
  1348. while(Character.getType(c) == Character.NON_SPACING_MARK) {
  1349. sequenceBuffer.appendCodePoint(c);
  1350. i += Character.charCount(c);
  1351. if (i >= normalizedPattern.length())
  1352. break;
  1353. c = normalizedPattern.codePointAt(i);
  1354. }
  1355. String ea = produceEquivalentAlternation(
  1356. sequenceBuffer.toString());
  1357. charClass.setLength(charClass.length()-Character.charCount(lastCodePoint));
  1358. if (eq == null)
  1359. eq = new StringBuilder();
  1360. eq.append('|');
  1361. eq.append(ea);
  1362. } else {
  1363. charClass.appendCodePoint(c);
  1364. i++;
  1365. }
  1366. if (i == normalizedPattern.length())
  1367. throw error("Unclosed character class");
  1368. lastCodePoint = c;
  1369. }
  1370. if (eq != null) {
  1371. result = "(?:"+charClass.toString()+eq.toString()+")";
  1372. } else {
  1373. result = charClass.toString();
  1374. }
  1375. newPattern.append(result);
  1376. return i;
  1377. }
  1378. /**
  1379. * Given a specific sequence composed of a regular character and
  1380. * combining marks that follow it, produce the alternation that will
  1381. * match all canonical equivalences of that sequence.
  1382. */
  1383. private String produceEquivalentAlternation(String source) {
  1384. int len = countChars(source, 0, 1);
  1385. if (source.length() == len)
  1386. // source has one character.
  1387. return source;
  1388. String base = source.substring(0,len);
  1389. String combiningMarks = source.substring(len);
  1390. String[] perms = producePermutations(combiningMarks);
  1391. StringBuilder result = new StringBuilder(source);
  1392. // Add combined permutations
  1393. for(int x=0; x<perms.length; x++) {
  1394. String next = base + perms[x];
  1395. if (x>0)
  1396. result.append("|"+next);
  1397. next = composeOneStep(next);
  1398. if (next != null)
  1399. result.append("|"+produceEquivalentAlternation(next));
  1400. }
  1401. return result.toString();
  1402. }
  1403. /**
  1404. * Returns an array of strings that have all the possible
  1405. * permutations of the characters in the input string.
  1406. * This is used to get a list of all possible orderings
  1407. * of a set of combining marks. Note that some of the permutations
  1408. * are invalid because of combining class collisions, and these
  1409. * possibilities must be removed because they are not canonically
  1410. * equivalent.
  1411. */
  1412. private String[] producePermutations(String input) {
  1413. if (input.length() == countChars(input, 0, 1))
  1414. return new String[] {input};
  1415. if (input.length() == countChars(input, 0, 2)) {
  1416. int c0 = Character.codePointAt(input, 0);
  1417. int c1 = Character.codePointAt(input, Character.charCount(c0));
  1418. if (getClass(c1) == getClass(c0)) {
  1419. return new String[] {input};
  1420. }
  1421. String[] result = new String[2];
  1422. result[0] = input;
  1423. StringBuilder sb = new StringBuilder(2);
  1424. sb.appendCodePoint(c1);
  1425. sb.appendCodePoint(c0);
  1426. result[1] = sb.toString();
  1427. return result;
  1428. }
  1429. int length = 1;
  1430. int nCodePoints = countCodePoints(input);
  1431. for(int x=1; x<nCodePoints; x++)
  1432. length = length * (x+1);
  1433. String[] temp = new String[length];
  1434. int combClass[] = new int[nCodePoints];
  1435. for(int x=0, i=0; x<nCodePoints; x++) {
  1436. int c = Character.codePointAt(input, i);
  1437. combClass[x] = getClass(c);
  1438. i += Character.charCount(c);
  1439. }
  1440. // For each char, take it out and add the permutations
  1441. // of the remaining chars
  1442. int index = 0;
  1443. int len;
  1444. // offset maintains the index in code units.
  1445. loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
  1446. len = countChars(input, offset, 1);
  1447. boolean skip = false;
  1448. for(int y=x-1; y>=0; y--) {
  1449. if (combClass[y] == combClass[x]) {
  1450. continue loop;
  1451. }
  1452. }
  1453. StringBuilder sb = new StringBuilder(input);
  1454. String otherChars = sb.delete(offset, offset+len).toString();
  1455. String[] subResult = producePermutations(otherChars);
  1456. String prefix = input.substring(offset, offset+len);
  1457. for(int y=0; y<subResult.length; y++)
  1458. temp[index++] = prefix + subResult[y];
  1459. }
  1460. String[] result = new String[index];
  1461. for (int x=0; x<index; x++)
  1462. result[x] = temp[x];
  1463. return result;
  1464. }
  1465. private int getClass(int c) {
  1466. return sun.text.Normalizer.getCombiningClass(c);
  1467. }
  1468. /**
  1469. * Attempts to compose input by combining the first character
  1470. * with the first combining mark following it. Returns a String
  1471. * that is the composition of the leading character with its first
  1472. * combining mark followed by the remaining combining marks. Returns
  1473. * null if the first two characters cannot be further composed.
  1474. */
  1475. private String composeOneStep(String input) {
  1476. int len = countChars(input, 0, 2);
  1477. String firstTwoCharacters = input.substring(0, len);
  1478. String result = Normalizer.normalize(firstTwoCharacters, Normalizer.Form.NFC);
  1479. if (result.equals(firstTwoCharacters))
  1480. return null;
  1481. else {
  1482. String remainder = input.substring(len);
  1483. return result + remainder;
  1484. }
  1485. }
  1486. /**
  1487. * Preprocess any \Q...\E sequences in `temp', meta-quoting them.
  1488. * See the description of `quotemeta' in perlfunc(1).
  1489. */
  1490. private void RemoveQEQuoting() {
  1491. final int pLen = patternLength;
  1492. int i = 0;
  1493. while (i < pLen-1) {
  1494. if (temp[i] != '\\')
  1495. i += 1;
  1496. else if (temp[i + 1] != 'Q')
  1497. i += 2;
  1498. else
  1499. break;
  1500. }
  1501. if (i >= pLen - 1) // No \Q sequence found
  1502. return;
  1503. int j = i;
  1504. i += 2;
  1505. int[] newtemp = new int[j + 2*(pLen-i) + 2];
  1506. System.arraycopy(temp, 0, newtemp, 0, j);
  1507. boolean inQuote = true;
  1508. while (i < pLen) {
  1509. int c = temp[i++];
  1510. if (! ASCII.isAscii(c) || ASCII.isAlnum(c)) {
  1511. newtemp[j++] = c;
  1512. } else if (c != '\\') {
  1513. if (inQuote) newtemp[j++] = '\\';
  1514. newtemp[j++] = c;
  1515. } else if (inQuote) {
  1516. if (temp[i] == 'E') {
  1517. i++;
  1518. inQuote = false;
  1519. } else {
  1520. newtemp[j++] = '\\';
  1521. newtemp[j++] = '\\';
  1522. }
  1523. } else {
  1524. if (temp[i] == 'Q') {
  1525. i++;
  1526. inQuote = true;
  1527. } else {
  1528. newtemp[j++] = c;
  1529. if (i != pLen)
  1530. newtemp[j++] = temp[i++];
  1531. }
  1532. }
  1533. }
  1534. patternLength = j;
  1535. temp = Arrays.copyOf(newtemp, j + 2); // double zero termination
  1536. }
  1537. /**
  1538. * Copies regular expression to an int array and invokes the parsing
  1539. * of the expression which will create the object tree.
  1540. */
  1541. private void compile() {
  1542. // Handle canonical equivalences
  1543. if (has(CANON_EQ) && !has(LITERAL)) {
  1544. normalize();
  1545. } else {
  1546. normalizedPattern = pattern;
  1547. }
  1548. patternLength = normalizedPattern.length();
  1549. // Copy pattern to int array for convenience
  1550. // Use double zero to terminate pattern
  1551. temp = new int[patternLength + 2];
  1552. hasSupplementary = false;
  1553. int c, count = 0;
  1554. // Convert all chars into code points
  1555. for (int x = 0; x < patternLength; x += Character.charCount(c)) {
  1556. c = normalizedPattern.codePointAt(x);
  1557. if (isSupplementary(c)) {
  1558. hasSupplementary = true;
  1559. }
  1560. temp[count++] = c;
  1561. }
  1562. patternLength = count; // patternLength now in code points
  1563. if (! has(LITERAL))
  1564. RemoveQEQuoting();
  1565. // Allocate all temporary objects here.
  1566. buffer = new int[32];
  1567. groupNodes = new GroupHead[10];
  1568. namedGroups = null;
  1569. if (has(LITERAL)) {
  1570. // Literal pattern handling
  1571. matchRoot = newSlice(temp, patternLength, hasSupplementary);
  1572. matchRoot.next = lastAccept;
  1573. } else {
  1574. // Start recursive descent parsing
  1575. matchRoot = expr(lastAccept);
  1576. // Check extra pattern characters
  1577. if (patternLength != cursor) {
  1578. if (peek() == ')') {
  1579. throw error("Unmatched closing ')'");
  1580. } else {
  1581. throw error("Unexpected internal error");
  1582. }
  1583. }
  1584. }
  1585. // Peephole optimization
  1586. if (matchRoot instanceof Slice) {
  1587. root = BnM.optimize(matchRoot);
  1588. if (root == matchRoot) {
  1589. root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
  1590. }
  1591. } else if (matchRoot instanceof Begin || matchRoot instanceof First) {
  1592. root = matchRoot;
  1593. } else {
  1594. root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
  1595. }
  1596. // Release temporary storage
  1597. temp = null;
  1598. buffer = null;
  1599. groupNodes = null;
  1600. patternLength = 0;
  1601. compiled = true;
  1602. }
  1603. Map<String, Integer> namedGroups() {
  1604. if (namedGroups == null)
  1605. namedGroups = new HashMap<>(2);
  1606. return namedGroups;
  1607. }
  1608. /**
  1609. * Used to print out a subtree of the Pattern to help with debugging.
  1610. */
  1611. private static void printObjectTree(Node node) {
  1612. while(node != null) {
  1613. if (node instanceof Prolog) {
  1614. System.out.println(node);
  1615. printObjectTree(((Prolog)node).loop);
  1616. System.out.println("**** end contents prolog loop");
  1617. } else if (node instanceof Loop) {
  1618. System.out.println(node);
  1619. printObjectTree(((Loop)node).body);
  1620. System.out.println("**** end contents Loop body");
  1621. } else if (node instanceof Curly) {
  1622. System.out.println(node);
  1623. printObjectTree(((Curly)node).atom);
  1624. System.out.println("**** end contents Curly body");
  1625. } else if (node instanceof GroupCurly) {
  1626. System.out.println(node);
  1627. printObjectTree(((GroupCurly)node).atom);
  1628. System.out.println("**** end contents GroupCurly body");
  1629. } else if (node instanceof GroupTail) {
  1630. System.out.println(node);
  1631. System.out.println("Tail next is "+node.next);
  1632. return;
  1633. } else {
  1634. System.out.println(node);
  1635. }
  1636. node = node.next;
  1637. if (node != null)
  1638. System.out.println("->next:");
  1639. if (node == Pattern.accept) {
  1640. System.out.println("Accept Node");
  1641. node = null;
  1642. }
  1643. }
  1644. }
  1645. /**
  1646. * Used to accumulate information about a subtree of the object graph
  1647. * so that optimizations can be applied to the subtree.
  1648. */
  1649. static final class TreeInfo {
  1650. int minLength;
  1651. int maxLength;
  1652. boolean maxValid;
  1653. boolean deterministic;
  1654. TreeInfo() {
  1655. reset();
  1656. }
  1657. void reset() {
  1658. minLength = 0;
  1659. maxLength = 0;
  1660. maxValid = true;
  1661. deterministic = true;
  1662. }
  1663. }
  1664. /*
  1665. * The following private methods are mainly used to improve the
  1666. * readability of the code. In order to let the Java compiler easily
  1667. * inline them, we should not put many assertions or error checks in them.
  1668. */
  1669. /**
  1670. * Indicates whether a particular flag is set or not.
  1671. */
  1672. private boolean has(int f) {
  1673. return (flags & f) != 0;
  1674. }
  1675. /**
  1676. * Match next character, signal error if failed.
  1677. */
  1678. private void accept(int ch, String s) {
  1679. int testChar = temp[cursor++];
  1680. if (has(COMMENTS))
  1681. testChar = parsePastWhitespace(testChar);
  1682. if (ch != testChar) {
  1683. throw error(s);
  1684. }
  1685. }
  1686. /**
  1687. * Mark the end of pattern with a specific character.
  1688. */
  1689. private void mark(int c) {
  1690. temp[patternLength] = c;
  1691. }
  1692. /**
  1693. * Peek the next character, and do not advance the cursor.
  1694. */
  1695. private int peek() {
  1696. int ch = temp[cursor];
  1697. if (has(COMMENTS))
  1698. ch = peekPastWhitespace(ch);
  1699. return ch;
  1700. }
  1701. /**
  1702. * Read the next character, and advance the cursor by one.
  1703. */
  1704. private int read() {
  1705. int ch = temp[cursor++];
  1706. if (has(COMMENTS))
  1707. ch = parsePastWhitespace(ch);
  1708. return ch;
  1709. }
  1710. /**
  1711. * Read the next character, and advance the cursor by one,
  1712. * ignoring the COMMENTS setting
  1713. */
  1714. private int readEscaped() {
  1715. int ch = temp[cursor++];
  1716. return ch;
  1717. }
  1718. /**
  1719. * Advance the cursor by one, and peek the next character.
  1720. */
  1721. private int next() {
  1722. int ch = temp[++cursor];
  1723. if (has(COMMENTS))
  1724. ch = peekPastWhitespace(ch);
  1725. return ch;
  1726. }
  1727. /**
  1728. * Advance the cursor by one, and peek the next character,
  1729. * ignoring the COMMENTS setting
  1730. */
  1731. private int nextEscaped() {
  1732. int ch = temp[++cursor];
  1733. return ch;
  1734. }
  1735. /**
  1736. * If in xmode peek past whitespace and comments.
  1737. */
  1738. private int peekPastWhitespace(int ch) {
  1739. while (ASCII.isSpace(ch) || ch == '#') {
  1740. while (ASCII.isSpace(ch))
  1741. ch = temp[++cursor];
  1742. if (ch == '#') {
  1743. ch = peekPastLine();
  1744. }
  1745. }
  1746. return ch;
  1747. }
  1748. /**
  1749. * If in xmode parse past whitespace and comments.
  1750. */
  1751. private int parsePastWhitespace(int ch) {
  1752. while (ASCII.isSpace(ch) || ch == '#') {
  1753. while (ASCII.isSpace(ch))
  1754. ch = temp[cursor++];
  1755. if (ch == '#')
  1756. ch = parsePastLine();
  1757. }
  1758. return ch;
  1759. }
  1760. /**
  1761. * xmode parse past comment to end of line.
  1762. */
  1763. private int parsePastLine() {
  1764. int ch = temp[cursor++];
  1765. while (ch != 0 && !isLineSeparator(ch))
  1766. ch = temp[cursor++];
  1767. return ch;
  1768. }
  1769. /**
  1770. * xmode peek past comment to end of line.
  1771. */
  1772. private int peekPastLine() {
  1773. int ch = temp[++cursor];
  1774. while (ch != 0 && !isLineSeparator(ch))
  1775. ch = temp[++cursor];
  1776. return ch;
  1777. }
  1778. /**
  1779. * Determines if character is a line separator in the current mode
  1780. */
  1781. private boolean isLineSeparator(int ch) {
  1782. if (has(UNIX_LINES)) {
  1783. return ch == '\n';
  1784. } else {
  1785. return (ch == '\n' ||
  1786. ch == '\r' ||
  1787. (ch|1) == '\u2029' ||
  1788. ch == '\u0085');
  1789. }
  1790. }
  1791. /**
  1792. * Read the character after the next one, and advance the cursor by two.
  1793. */
  1794. private int skip() {
  1795. int i = cursor;
  1796. int ch = temp[i+1];
  1797. cursor = i + 2;
  1798. return ch;
  1799. }
  1800. /**
  1801. * Unread one next character, and retreat cursor by one.
  1802. */
  1803. private void unread() {
  1804. cursor--;
  1805. }
  1806. /**
  1807. * Internal method used for handling all syntax errors. The pattern is
  1808. * displayed with a pointer to aid in locating the syntax error.
  1809. */
  1810. private PatternSyntaxException error(String s) {
  1811. return new PatternSyntaxException(s, normalizedPattern, cursor - 1);
  1812. }
  1813. /**
  1814. * Determines if there is any supplementary character or unpaired
  1815. * surrogate in the specified range.
  1816. */
  1817. private boolean findSupplementary(int start, int end) {
  1818. for (int i = start; i < end; i++) {
  1819. if (isSupplementary(temp[i]))
  1820. return true;
  1821. }
  1822. return false;
  1823. }
  1824. /**
  1825. * Determines if the specified code point is a supplementary
  1826. * character or unpaired surrogate.
  1827. */
  1828. private static final boolean isSupplementary(int ch) {
  1829. return ch >= Character.MIN_SUPPLEMENTARY_CODE_POINT ||
  1830. Character.isSurrogate((char)ch);
  1831. }
  1832. /**
  1833. * The following methods handle the main parsing. They are sorted
  1834. * according to their precedence order, the lowest one first.
  1835. */
  1836. /**
  1837. * The expression is parsed with branch nodes added for alternations.
  1838. * This may be called recursively to parse sub expressions that may
  1839. * contain alternations.
  1840. */
  1841. private Node expr(Node end) {
  1842. Node prev = null;
  1843. Node firstTail = null;
  1844. Node branchConn = null;
  1845. for (;;) {
  1846. Node node = sequence(end);
  1847. Node nodeTail = root; //double return
  1848. if (prev == null) {
  1849. prev = node;
  1850. firstTail = nodeTail;
  1851. } else {
  1852. // Branch
  1853. if (branchConn == null) {
  1854. branchConn = new BranchConn();
  1855. branchConn.next = end;
  1856. }
  1857. if (node == end) {
  1858. // if the node returned from sequence() is "end"
  1859. // we have an empty expr, set a null atom into
  1860. // the branch to indicate to go "next" directly.
  1861. node = null;
  1862. } else {
  1863. // the "tail.next" of each atom goes to branchConn
  1864. nodeTail.next = branchConn;
  1865. }
  1866. if (prev instanceof Branch) {
  1867. ((Branch)prev).add(node);
  1868. } else {
  1869. if (prev == end) {
  1870. prev = null;
  1871. } else {
  1872. // replace the "end" with "branchConn" at its tail.next
  1873. // when put the "prev" into the branch as the first atom.
  1874. firstTail.next = branchConn;
  1875. }
  1876. prev = new Branch(prev, node, branchConn);
  1877. }
  1878. }
  1879. if (peek() != '|') {
  1880. return prev;
  1881. }
  1882. next();
  1883. }
  1884. }
  1885. /**
  1886. * Parsing of sequences between alternations.
  1887. */
  1888. private Node sequence(Node end) {
  1889. Node head = null;
  1890. Node tail = null;
  1891. Node node = null;
  1892. LOOP:
  1893. for (;;) {
  1894. int ch = peek();
  1895. switch (ch) {
  1896. case '(':
  1897. // Because group handles its own closure,
  1898. // we need to treat it differently
  1899. node = group0();
  1900. // Check for comment or flag group
  1901. if (node == null)
  1902. continue;
  1903. if (head == null)
  1904. head = node;
  1905. else
  1906. tail.next = node;
  1907. // Double return: Tail was returned in root
  1908. tail = root;
  1909. continue;
  1910. case '[':
  1911. node = clazz(true);
  1912. break;
  1913. case '\\':
  1914. ch = nextEscaped();
  1915. if (ch == 'p' || ch == 'P') {
  1916. boolean oneLetter = true;
  1917. boolean comp = (ch == 'P');
  1918. ch = next(); // Consume { if present
  1919. if (ch != '{') {
  1920. unread();
  1921. } else {
  1922. oneLetter = false;
  1923. }
  1924. node = family(oneLetter, comp);
  1925. } else {
  1926. unread();
  1927. node = atom();
  1928. }
  1929. break;
  1930. case '^':
  1931. next();
  1932. if (has(MULTILINE)) {
  1933. if (has(UNIX_LINES))
  1934. node = new UnixCaret();
  1935. else
  1936. node = new Caret();
  1937. } else {
  1938. node = new Begin();
  1939. }
  1940. break;
  1941. case '$':
  1942. next();
  1943. if (has(UNIX_LINES))
  1944. node = new UnixDollar(has(MULTILINE));
  1945. else
  1946. node = new Dollar(has(MULTILINE));
  1947. break;
  1948. case '.':
  1949. next();
  1950. if (has(DOTALL)) {
  1951. node = new All();
  1952. } else {
  1953. if (has(UNIX_LINES))
  1954. node = new UnixDot();
  1955. else {
  1956. node = new Dot();
  1957. }
  1958. }
  1959. break;
  1960. case '|':
  1961. case ')':
  1962. break LOOP;
  1963. case ']': // Now interpreting dangling ] and } as literals
  1964. case '}':
  1965. node = atom();
  1966. break;
  1967. case '?':
  1968. case '*':
  1969. case '+':
  1970. next();
  1971. throw error("Dangling meta character '" + ((char)ch) + "'");
  1972. case 0:
  1973. if (cursor >= patternLength) {
  1974. break LOOP;
  1975. }
  1976. // Fall through
  1977. default:
  1978. node = atom();
  1979. break;
  1980. }
  1981. node = closure(node);
  1982. if (head == null) {
  1983. head = tail = node;
  1984. } else {
  1985. tail.next = node;
  1986. tail = node;
  1987. }
  1988. }
  1989. if (head == null) {
  1990. return end;
  1991. }
  1992. tail.next = end;
  1993. root = tail; //double return
  1994. return head;
  1995. }
  1996. /**
  1997. * Parse and add a new Single or Slice.
  1998. */
  1999. private Node atom() {
  2000. int first = 0;
  2001. int prev = -1;
  2002. boolean hasSupplementary = false;
  2003. int ch = peek();
  2004. for (;;) {
  2005. switch (ch) {
  2006. case '*':
  2007. case '+':
  2008. case '?':
  2009. case '{':
  2010. if (first > 1) {
  2011. cursor = prev; // Unwind one character
  2012. first--;
  2013. }
  2014. break;
  2015. case '$':
  2016. case '.':
  2017. case '^':
  2018. case '(':
  2019. case '[':
  2020. case '|':
  2021. case ')':
  2022. break;
  2023. case '\\':
  2024. ch = nextEscaped();
  2025. if (ch == 'p' || ch == 'P') { // Property
  2026. if (first > 0) { // Slice is waiting; handle it first
  2027. unread();
  2028. break;
  2029. } else { // No slice; just return the family node
  2030. boolean comp = (ch == 'P');
  2031. boolean oneLetter = true;
  2032. ch = next(); // Consume { if present
  2033. if (ch != '{')
  2034. unread();
  2035. else
  2036. oneLetter = false;
  2037. return family(oneLetter, comp);
  2038. }
  2039. }
  2040. unread();
  2041. prev = cursor;
  2042. ch = escape(false, first == 0);
  2043. if (ch >= 0) {
  2044. append(ch, first);
  2045. first++;
  2046. if (isSupplementary(ch)) {
  2047. hasSupplementary = true;
  2048. }
  2049. ch = peek();
  2050. continue;
  2051. } else if (first == 0) {
  2052. return root;
  2053. }
  2054. // Unwind meta escape sequence
  2055. cursor = prev;
  2056. break;
  2057. case 0:
  2058. if (cursor >= patternLength) {
  2059. break;
  2060. }
  2061. // Fall through
  2062. default:
  2063. prev = cursor;
  2064. append(ch, first);
  2065. first++;
  2066. if (isSupplementary(ch)) {
  2067. hasSupplementary = true;
  2068. }
  2069. ch = next();
  2070. continue;
  2071. }
  2072. break;
  2073. }
  2074. if (first == 1) {
  2075. return newSingle(buffer[0]);
  2076. } else {
  2077. return newSlice(buffer, first, hasSupplementary);
  2078. }
  2079. }
  2080. private void append(int ch, int len) {
  2081. if (len >= buffer.length) {
  2082. int[] tmp = new int[len+len];
  2083. System.arraycopy(buffer, 0, tmp, 0, len);
  2084. buffer = tmp;
  2085. }
  2086. buffer[len] = ch;
  2087. }
  2088. /**
  2089. * Parses a backref greedily, taking as many numbers as it
  2090. * can. The first digit is always treated as a backref, but
  2091. * multi digit numbers are only treated as a backref if at
  2092. * least that many backrefs exist at this point in the regex.
  2093. */
  2094. private Node ref(int refNum) {
  2095. boolean done = false;
  2096. while(!done) {
  2097. int ch = peek();
  2098. switch(ch) {
  2099. case '0':
  2100. case '1':
  2101. case '2':
  2102. case '3':
  2103. case '4':
  2104. case '5':
  2105. case '6':
  2106. case '7':
  2107. case '8':
  2108. case '9':
  2109. int newRefNum = (refNum * 10) + (ch - '0');
  2110. // Add another number if it doesn't make a group
  2111. // that doesn't exist
  2112. if (capturingGroupCount - 1 < newRefNum) {
  2113. done = true;
  2114. break;
  2115. }
  2116. refNum = newRefNum;
  2117. read();
  2118. break;
  2119. default:
  2120. done = true;
  2121. break;
  2122. }
  2123. }
  2124. if (has(CASE_INSENSITIVE))
  2125. return new CIBackRef(refNum, has(UNICODE_CASE));
  2126. else
  2127. return new BackRef(refNum);
  2128. }
  2129. /**
  2130. * Parses an escape sequence to determine the actual value that needs
  2131. * to be matched.
  2132. * If -1 is returned and create was true a new object was added to the tree
  2133. * to handle the escape sequence.
  2134. * If the returned value is greater than zero, it is the value that
  2135. * matches the escape sequence.
  2136. */
  2137. private int escape(boolean inclass, boolean create) {
  2138. int ch = skip();
  2139. switch (ch) {
  2140. case '0':
  2141. return o();
  2142. case '1':
  2143. case '2':
  2144. case '3':
  2145. case '4':
  2146. case '5':
  2147. case '6':
  2148. case '7':
  2149. case '8':
  2150. case '9':
  2151. if (inclass) break;
  2152. if (create) {
  2153. root = ref((ch - '0'));
  2154. }
  2155. return -1;
  2156. case 'A':
  2157. if (inclass) break;
  2158. if (create) root = new Begin();
  2159. return -1;
  2160. case 'B':
  2161. if (inclass) break;
  2162. if (create) root = new Bound(Bound.NONE, has(UNICODE_CHARACTER_CLASS));
  2163. return -1;
  2164. case 'C':
  2165. break;
  2166. case 'D':
  2167. if (create) root = has(UNICODE_CHARACTER_CLASS)
  2168. ? new Utype(UnicodeProp.DIGIT).complement()
  2169. : new Ctype(ASCII.DIGIT).complement();
  2170. return -1;
  2171. case 'E':
  2172. case 'F':
  2173. break;
  2174. case 'G':
  2175. if (inclass) break;
  2176. if (create) root = new LastMatch();
  2177. return -1;
  2178. case 'H':
  2179. case 'I':
  2180. case 'J':
  2181. case 'K':
  2182. case 'L':
  2183. case 'M':
  2184. case 'N':
  2185. case 'O':
  2186. case 'P':
  2187. case 'Q':
  2188. case 'R':
  2189. break;
  2190. case 'S':
  2191. if (create) root = has(UNICODE_CHARACTER_CLASS)
  2192. ? new Utype(UnicodeProp.WHITE_SPACE).complement()
  2193. : new Ctype(ASCII.SPACE).complement();
  2194. return -1;
  2195. case 'T':
  2196. case 'U':
  2197. case 'V':
  2198. break;
  2199. case 'W':
  2200. if (create) root = has(UNICODE_CHARACTER_CLASS)
  2201. ? new Utype(UnicodeProp.WORD).complement()
  2202. : new Ctype(ASCII.WORD).complement();
  2203. return -1;
  2204. case 'X':
  2205. case 'Y':
  2206. break;
  2207. case 'Z':
  2208. if (inclass) break;
  2209. if (create) {
  2210. if (has(UNIX_LINES))
  2211. root = new UnixDollar(false);
  2212. else
  2213. root = new Dollar(false);
  2214. }
  2215. return -1;
  2216. case 'a':
  2217. return '\007';
  2218. case 'b':
  2219. if (inclass) break;
  2220. if (create) root = new Bound(Bound.BOTH, has(UNICODE_CHARACTER_CLASS));
  2221. return -1;
  2222. case 'c':
  2223. return c();
  2224. case 'd':
  2225. if (create) root = has(UNICODE_CHARACTER_CLASS)
  2226. ? new Utype(UnicodeProp.DIGIT)
  2227. : new Ctype(ASCII.DIGIT);
  2228. return -1;
  2229. case 'e':
  2230. return '\033';
  2231. case 'f':
  2232. return '\f';
  2233. case 'g':
  2234. case 'h':
  2235. case 'i':
  2236. case 'j':
  2237. break;
  2238. case 'k':
  2239. if (inclass)
  2240. break;
  2241. if (read() != '<')
  2242. throw error("\\k is not followed by '<' for named capturing group");
  2243. String name = groupname(read());
  2244. if (!namedGroups().containsKey(name))
  2245. throw error("(named capturing group <"+ name+"> does not exit");
  2246. if (create) {
  2247. if (has(CASE_INSENSITIVE))
  2248. root = new CIBackRef(namedGroups().get(name), has(UNICODE_CASE));
  2249. else
  2250. root = new BackRef(namedGroups().get(name));
  2251. }
  2252. return -1;
  2253. case 'l':
  2254. case 'm':
  2255. break;
  2256. case 'n':
  2257. return '\n';
  2258. case 'o':
  2259. case 'p':
  2260. case 'q':
  2261. break;
  2262. case 'r':
  2263. return '\r';
  2264. case 's':
  2265. if (create) root = has(UNICODE_CHARACTER_CLASS)
  2266. ? new Utype(UnicodeProp.WHITE_SPACE)
  2267. : new Ctype(ASCII.SPACE);
  2268. return -1;
  2269. case 't':
  2270. return '\t';
  2271. case 'u':
  2272. return u();
  2273. case 'v':
  2274. return '\013';
  2275. case 'w':
  2276. if (create) root = has(UNICODE_CHARACTER_CLASS)
  2277. ? new Utype(UnicodeProp.WORD)
  2278. : new Ctype(ASCII.WORD);
  2279. return -1;
  2280. case 'x':
  2281. return x();
  2282. case 'y':
  2283. break;
  2284. case 'z':
  2285. if (inclass) break;
  2286. if (create) root = new End();
  2287. return -1;
  2288. default:
  2289. return ch;
  2290. }
  2291. throw error("Illegal/unsupported escape sequence");
  2292. }
  2293. /**
  2294. * Parse a character class, and return the node that matches it.
  2295. *
  2296. * Consumes a ] on the way out if consume is true. Usually consume
  2297. * is true except for the case of [abc&&def] where def is a separate
  2298. * right hand node with "understood" brackets.
  2299. */
  2300. private CharProperty clazz(boolean consume) {
  2301. CharProperty prev = null;
  2302. CharProperty node = null;
  2303. BitClass bits = new BitClass();
  2304. boolean include = true;
  2305. boolean firstInClass = true;
  2306. int ch = next();
  2307. for (;;) {
  2308. switch (ch) {
  2309. case '^':
  2310. // Negates if first char in a class, otherwise literal
  2311. if (firstInClass) {
  2312. if (temp[cursor-1] != '[')
  2313. break;
  2314. ch = next();
  2315. include = !include;
  2316. continue;
  2317. } else {
  2318. // ^ not first in class, treat as literal
  2319. break;
  2320. }
  2321. case '[':
  2322. firstInClass = false;
  2323. node = clazz(true);
  2324. if (prev == null)
  2325. prev = node;
  2326. else
  2327. prev = union(prev, node);
  2328. ch = peek();
  2329. continue;
  2330. case '&':
  2331. firstInClass = false;
  2332. ch = next();
  2333. if (ch == '&') {
  2334. ch = next();
  2335. CharProperty rightNode = null;
  2336. while (ch != ']' && ch != '&') {
  2337. if (ch == '[') {
  2338. if (rightNode == null)
  2339. rightNode = clazz(true);
  2340. else
  2341. rightNode = union(rightNode, clazz(true));
  2342. } else { // abc&&def
  2343. unread();
  2344. rightNode = clazz(false);
  2345. }
  2346. ch = peek();
  2347. }
  2348. if (rightNode != null)
  2349. node = rightNode;
  2350. if (prev == null) {
  2351. if (rightNode == null)
  2352. throw error("Bad class syntax");
  2353. else
  2354. prev = rightNode;
  2355. } else {
  2356. prev = intersection(prev, node);
  2357. }
  2358. } else {
  2359. // treat as a literal &
  2360. unread();
  2361. break;
  2362. }
  2363. continue;
  2364. case 0:
  2365. firstInClass = false;
  2366. if (cursor >= patternLength)
  2367. throw error("Unclosed character class");
  2368. break;
  2369. case ']':
  2370. firstInClass = false;
  2371. if (prev != null) {
  2372. if (consume)
  2373. next();
  2374. return prev;
  2375. }
  2376. break;
  2377. default:
  2378. firstInClass = false;
  2379. break;
  2380. }
  2381. node = range(bits);
  2382. if (include) {
  2383. if (prev == null) {
  2384. prev = node;
  2385. } else {
  2386. if (prev != node)
  2387. prev = union(prev, node);
  2388. }
  2389. } else {
  2390. if (prev == null) {
  2391. prev = node.complement();
  2392. } else {
  2393. if (prev != node)
  2394. prev = setDifference(prev, node);
  2395. }
  2396. }
  2397. ch = peek();
  2398. }
  2399. }
  2400. private CharProperty bitsOrSingle(BitClass bits, int ch) {
  2401. /* Bits can only handle codepoints in [u+0000-u+00ff] range.
  2402. Use "single" node instead of bits when dealing with unicode
  2403. case folding for codepoints listed below.
  2404. (1)Uppercase out of range: u+00ff, u+00b5
  2405. toUpperCase(u+00ff) -> u+0178
  2406. toUpperCase(u+00b5) -> u+039c
  2407. (2)LatinSmallLetterLongS u+17f
  2408. toUpperCase(u+017f) -> u+0053
  2409. (3)LatinSmallLetterDotlessI u+131
  2410. toUpperCase(u+0131) -> u+0049
  2411. (4)LatinCapitalLetterIWithDotAbove u+0130
  2412. toLowerCase(u+0130) -> u+0069
  2413. (5)KelvinSign u+212a
  2414. toLowerCase(u+212a) ==> u+006B
  2415. (6)AngstromSign u+212b
  2416. toLowerCase(u+212b) ==> u+00e5
  2417. */
  2418. int d;
  2419. if (ch < 256 &&
  2420. !(has(CASE_INSENSITIVE) && has(UNICODE_CASE) &&
  2421. (ch == 0xff || ch == 0xb5 ||
  2422. ch == 0x49 || ch == 0x69 || //I and i
  2423. ch == 0x53 || ch == 0x73 || //S and s
  2424. ch == 0x4b || ch == 0x6b || //K and k
  2425. ch == 0xc5 || ch == 0xe5))) //A+ring
  2426. return bits.add(ch, flags());
  2427. return newSingle(ch);
  2428. }
  2429. /**
  2430. * Parse a single character or a character range in a character class
  2431. * and return its representative node.
  2432. */
  2433. private CharProperty range(BitClass bits) {
  2434. int ch = peek();
  2435. if (ch == '\\') {
  2436. ch = nextEscaped();
  2437. if (ch == 'p' || ch == 'P') { // A property
  2438. boolean comp = (ch == 'P');
  2439. boolean oneLetter = true;
  2440. // Consume { if present
  2441. ch = next();
  2442. if (ch != '{')
  2443. unread();
  2444. else
  2445. oneLetter = false;
  2446. return family(oneLetter, comp);
  2447. } else { // ordinary escape
  2448. unread();
  2449. ch = escape(true, true);
  2450. if (ch == -1)
  2451. return (CharProperty) root;
  2452. }
  2453. } else {
  2454. ch = single();
  2455. }
  2456. if (ch >= 0) {
  2457. if (peek() == '-') {
  2458. int endRange = temp[cursor+1];
  2459. if (endRange == '[') {
  2460. return bitsOrSingle(bits, ch);
  2461. }
  2462. if (endRange != ']') {
  2463. next();
  2464. int m = single();
  2465. if (m < ch)
  2466. throw error("Illegal character range");
  2467. if (has(CASE_INSENSITIVE))
  2468. return caseInsensitiveRangeFor(ch, m);
  2469. else
  2470. return rangeFor(ch, m);
  2471. }
  2472. }
  2473. return bitsOrSingle(bits, ch);
  2474. }
  2475. throw error("Unexpected character '"+((char)ch)+"'");
  2476. }
  2477. private int single() {
  2478. int ch = peek();
  2479. switch (ch) {
  2480. case '\\':
  2481. return escape(true, false);
  2482. default:
  2483. next();
  2484. return ch;
  2485. }
  2486. }
  2487. /**
  2488. * Parses a Unicode character family and returns its representative node.
  2489. */
  2490. private CharProperty family(boolean singleLetter,
  2491. boolean maybeComplement)
  2492. {
  2493. next();
  2494. String name;
  2495. CharProperty node = null;
  2496. if (singleLetter) {
  2497. int c = temp[cursor];
  2498. if (!Character.isSupplementaryCodePoint(c)) {
  2499. name = String.valueOf((char)c);
  2500. } else {
  2501. name = new String(temp, cursor, 1);
  2502. }
  2503. read();
  2504. } else {
  2505. int i = cursor;
  2506. mark('}');
  2507. while(read() != '}') {
  2508. }
  2509. mark('\000');
  2510. int j = cursor;
  2511. if (j > patternLength)
  2512. throw error("Unclosed character family");
  2513. if (i + 1 >= j)
  2514. throw error("Empty character family");
  2515. name = new String(temp, i, j-i-1);
  2516. }
  2517. int i = name.indexOf('=');
  2518. if (i != -1) {
  2519. // property construct \p{name=value}
  2520. String value = name.substring(i + 1);
  2521. name = name.substring(0, i).toLowerCase(Locale.ENGLISH);
  2522. if ("sc".equals(name) || "script".equals(name)) {
  2523. node = unicodeScriptPropertyFor(value);
  2524. } else if ("blk".equals(name) || "block".equals(name)) {
  2525. node = unicodeBlockPropertyFor(value);
  2526. } else if ("gc".equals(name) || "general_category".equals(name)) {
  2527. node = charPropertyNodeFor(value);
  2528. } else {
  2529. throw error("Unknown Unicode property {name=<" + name + ">, "
  2530. + "value=<" + value + ">}");
  2531. }
  2532. } else {
  2533. if (name.startsWith("In")) {
  2534. // \p{inBlockName}
  2535. node = unicodeBlockPropertyFor(name.substring(2));
  2536. } else if (name.startsWith("Is")) {
  2537. // \p{isGeneralCategory} and \p{isScriptName}
  2538. name = name.substring(2);
  2539. UnicodeProp uprop = UnicodeProp.forName(name);
  2540. if (uprop != null)
  2541. node = new Utype(uprop);
  2542. if (node == null)
  2543. node = CharPropertyNames.charPropertyFor(name);
  2544. if (node == null)
  2545. node = unicodeScriptPropertyFor(name);
  2546. } else {
  2547. if (has(UNICODE_CHARACTER_CLASS)) {
  2548. UnicodeProp uprop = UnicodeProp.forPOSIXName(name);
  2549. if (uprop != null)
  2550. node = new Utype(uprop);
  2551. }
  2552. if (node == null)
  2553. node = charPropertyNodeFor(name);
  2554. }
  2555. }
  2556. if (maybeComplement) {
  2557. if (node instanceof Category || node instanceof Block)
  2558. hasSupplementary = true;
  2559. node = node.complement();
  2560. }
  2561. return node;
  2562. }
  2563. /**
  2564. * Returns a CharProperty matching all characters belong to
  2565. * a UnicodeScript.
  2566. */
  2567. private CharProperty unicodeScriptPropertyFor(String name) {
  2568. final Character.UnicodeScript script;
  2569. try {
  2570. script = Character.UnicodeScript.forName(name);
  2571. } catch (IllegalArgumentException iae) {
  2572. throw error("Unknown character script name {" + name + "}");
  2573. }
  2574. return new Script(script);
  2575. }
  2576. /**
  2577. * Returns a CharProperty matching all characters in a UnicodeBlock.
  2578. */
  2579. private CharProperty unicodeBlockPropertyFor(String name) {
  2580. final Character.UnicodeBlock block;
  2581. try {
  2582. block = Character.UnicodeBlock.forName(name);
  2583. } catch (IllegalArgumentException iae) {
  2584. throw error("Unknown character block name {" + name + "}");
  2585. }
  2586. return new Block(block);
  2587. }
  2588. /**
  2589. * Returns a CharProperty matching all characters in a named property.
  2590. */
  2591. private CharProperty charPropertyNodeFor(String name) {
  2592. CharProperty p = CharPropertyNames.charPropertyFor(name);
  2593. if (p == null)
  2594. throw error("Unknown character property name {" + name + "}");
  2595. return p;
  2596. }
  2597. /**
  2598. * Parses and returns the name of a "named capturing group", the trailing
  2599. * ">" is consumed after parsing.
  2600. */
  2601. private String groupname(int ch) {
  2602. StringBuilder sb = new StringBuilder();
  2603. sb.append(Character.toChars(ch));
  2604. while (ASCII.isLower(ch=read()) || ASCII.isUpper(ch) ||
  2605. ASCII.isDigit(ch)) {
  2606. sb.append(Character.toChars(ch));
  2607. }
  2608. if (sb.length() == 0)
  2609. throw error("named capturing group has 0 length name");
  2610. if (ch != '>')
  2611. throw error("named capturing group is missing trailing '>'");
  2612. return sb.toString();
  2613. }
  2614. /**
  2615. * Parses a group and returns the head node of a set of nodes that process
  2616. * the group. Sometimes a double return system is used where the tail is
  2617. * returned in root.
  2618. */
  2619. private Node group0() {
  2620. boolean capturingGroup = false;
  2621. Node head = null;
  2622. Node tail = null;
  2623. int save = flags;
  2624. root = null;
  2625. int ch = next();
  2626. if (ch == '?') {
  2627. ch = skip();
  2628. switch (ch) {
  2629. case ':': // (?:xxx) pure group
  2630. head = createGroup(true);
  2631. tail = root;
  2632. head.next = expr(tail);
  2633. break;
  2634. case '=': // (?=xxx) and (?!xxx) lookahead
  2635. case '!':
  2636. head = createGroup(true);
  2637. tail = root;
  2638. head.next = expr(tail);
  2639. if (ch == '=') {
  2640. head = tail = new Pos(head);
  2641. } else {
  2642. head = tail = new Neg(head);
  2643. }
  2644. break;
  2645. case '>': // (?>xxx) independent group
  2646. head = createGroup(true);
  2647. tail = root;
  2648. head.next = expr(tail);
  2649. head = tail = new Ques(head, INDEPENDENT);
  2650. break;
  2651. case '<': // (?<xxx) look behind
  2652. ch = read();
  2653. if (ASCII.isLower(ch) || ASCII.isUpper(ch)) {
  2654. // named captured group
  2655. String name = groupname(ch);
  2656. if (namedGroups().containsKey(name))
  2657. throw error("Named capturing group <" + name
  2658. + "> is already defined");
  2659. capturingGroup = true;
  2660. head = createGroup(false);
  2661. tail = root;
  2662. namedGroups().put(name, capturingGroupCount-1);
  2663. head.next = expr(tail);
  2664. break;
  2665. }
  2666. int start = cursor;
  2667. head = createGroup(true);
  2668. tail = root;
  2669. head.next = expr(tail);
  2670. tail.next = lookbehindEnd;
  2671. TreeInfo info = new TreeInfo();
  2672. head.study(info);
  2673. if (info.maxValid == false) {
  2674. throw error("Look-behind group does not have "
  2675. + "an obvious maximum length");
  2676. }
  2677. boolean hasSupplementary = findSupplementary(start, patternLength);
  2678. if (ch == '=') {
  2679. head = tail = (hasSupplementary ?
  2680. new BehindS(head, info.maxLength,
  2681. info.minLength) :
  2682. new Behind(head, info.maxLength,
  2683. info.minLength));
  2684. } else if (ch == '!') {
  2685. head = tail = (hasSupplementary ?
  2686. new NotBehindS(head, info.maxLength,
  2687. info.minLength) :
  2688. new NotBehind(head, info.maxLength,
  2689. info.minLength));
  2690. } else {
  2691. throw error("Unknown look-behind group");
  2692. }
  2693. break;
  2694. case '$':
  2695. case '@':
  2696. throw error("Unknown group type");
  2697. default: // (?xxx:) inlined match flags
  2698. unread();
  2699. addFlag();
  2700. ch = read();
  2701. if (ch == ')') {
  2702. return null; // Inline modifier only
  2703. }
  2704. if (ch != ':') {
  2705. throw error("Unknown inline modifier");
  2706. }
  2707. head = createGroup(true);
  2708. tail = root;
  2709. head.next = expr(tail);
  2710. break;
  2711. }
  2712. } else { // (xxx) a regular group
  2713. capturingGroup = true;
  2714. head = createGroup(false);
  2715. tail = root;
  2716. head.next = expr(tail);
  2717. }
  2718. accept(')', "Unclosed group");
  2719. flags = save;
  2720. // Check for quantifiers
  2721. Node node = closure(head);
  2722. if (node == head) { // No closure
  2723. root = tail;
  2724. return node; // Dual return
  2725. }
  2726. if (head == tail) { // Zero length assertion
  2727. root = node;
  2728. return node; // Dual return
  2729. }
  2730. if (node instanceof Ques) {
  2731. Ques ques = (Ques) node;
  2732. if (ques.type == POSSESSIVE) {
  2733. root = node;
  2734. return node;
  2735. }
  2736. tail.next = new BranchConn();
  2737. tail = tail.next;
  2738. if (ques.type == GREEDY) {
  2739. head = new Branch(head, null, tail);
  2740. } else { // Reluctant quantifier
  2741. head = new Branch(null, head, tail);
  2742. }
  2743. root = tail;
  2744. return head;
  2745. } else if (node instanceof Curly) {
  2746. Curly curly = (Curly) node;
  2747. if (curly.type == POSSESSIVE) {
  2748. root = node;
  2749. return node;
  2750. }
  2751. // Discover if the group is deterministic
  2752. TreeInfo info = new TreeInfo();
  2753. if (head.study(info)) { // Deterministic
  2754. GroupTail temp = (GroupTail) tail;
  2755. head = root = new GroupCurly(head.next, curly.cmin,
  2756. curly.cmax, curly.type,
  2757. ((GroupTail)tail).localIndex,
  2758. ((GroupTail)tail).groupIndex,
  2759. capturingGroup);
  2760. return head;
  2761. } else { // Non-deterministic
  2762. int temp = ((GroupHead) head).localIndex;
  2763. Loop loop;
  2764. if (curly.type == GREEDY)
  2765. loop = new Loop(this.localCount, temp);
  2766. else // Reluctant Curly
  2767. loop = new LazyLoop(this.localCount, temp);
  2768. Prolog prolog = new Prolog(loop);
  2769. this.localCount += 1;
  2770. loop.cmin = curly.cmin;
  2771. loop.cmax = curly.cmax;
  2772. loop.body = head;
  2773. tail.next = loop;
  2774. root = loop;
  2775. return prolog; // Dual return
  2776. }
  2777. }
  2778. throw error("Internal logic error");
  2779. }
  2780. /**
  2781. * Create group head and tail nodes using double return. If the group is
  2782. * created with anonymous true then it is a pure group and should not
  2783. * affect group counting.
  2784. */
  2785. private Node createGroup(boolean anonymous) {
  2786. int localIndex = localCount++;
  2787. int groupIndex = 0;
  2788. if (!anonymous)
  2789. groupIndex = capturingGroupCount++;
  2790. GroupHead head = new GroupHead(localIndex);
  2791. root = new GroupTail(localIndex, groupIndex);
  2792. if (!anonymous && groupIndex < 10)
  2793. groupNodes[groupIndex] = head;
  2794. return head;
  2795. }
  2796. /**
  2797. * Parses inlined match flags and set them appropriately.
  2798. */
  2799. private void addFlag() {
  2800. int ch = peek();
  2801. for (;;) {
  2802. switch (ch) {
  2803. case 'i':
  2804. flags |= CASE_INSENSITIVE;
  2805. break;
  2806. case 'm':
  2807. flags |= MULTILINE;
  2808. break;
  2809. case 's':
  2810. flags |= DOTALL;
  2811. break;
  2812. case 'd':
  2813. flags |= UNIX_LINES;
  2814. break;
  2815. case 'u':
  2816. flags |= UNICODE_CASE;
  2817. break;
  2818. case 'c':
  2819. flags |= CANON_EQ;
  2820. break;
  2821. case 'x':
  2822. flags |= COMMENTS;
  2823. break;
  2824. case 'U':
  2825. flags |= (UNICODE_CHARACTER_CLASS | UNICODE_CASE);
  2826. break;
  2827. case '-': // subFlag then fall through
  2828. ch = next();
  2829. subFlag();
  2830. default:
  2831. return;
  2832. }
  2833. ch = next();
  2834. }
  2835. }
  2836. /**
  2837. * Parses the second part of inlined match flags and turns off
  2838. * flags appropriately.
  2839. */
  2840. private void subFlag() {
  2841. int ch = peek();
  2842. for (;;) {
  2843. switch (ch) {
  2844. case 'i':
  2845. flags &= ~CASE_INSENSITIVE;
  2846. break;
  2847. case 'm':
  2848. flags &= ~MULTILINE;
  2849. break;
  2850. case 's':
  2851. flags &= ~DOTALL;
  2852. break;
  2853. case 'd':
  2854. flags &= ~UNIX_LINES;
  2855. break;
  2856. case 'u':
  2857. flags &= ~UNICODE_CASE;
  2858. break;
  2859. case 'c':
  2860. flags &= ~CANON_EQ;
  2861. break;
  2862. case 'x':
  2863. flags &= ~COMMENTS;
  2864. break;
  2865. case 'U':
  2866. flags &= ~(UNICODE_CHARACTER_CLASS | UNICODE_CASE);
  2867. default:
  2868. return;
  2869. }
  2870. ch = next();
  2871. }
  2872. }
  2873. static final int MAX_REPS = 0x7FFFFFFF;
  2874. static final int GREEDY = 0;
  2875. static final int LAZY = 1;
  2876. static final int POSSESSIVE = 2;
  2877. static final int INDEPENDENT = 3;
  2878. /**
  2879. * Processes repetition. If the next character peeked is a quantifier
  2880. * then new nodes must be appended to handle the repetition.
  2881. * Prev could be a single or a group, so it could be a chain of nodes.
  2882. */
  2883. private Node closure(Node prev) {
  2884. Node atom;
  2885. int ch = peek();
  2886. switch (ch) {
  2887. case '?':
  2888. ch = next();
  2889. if (ch == '?') {
  2890. next();
  2891. return new Ques(prev, LAZY);
  2892. } else if (ch == '+') {
  2893. next();
  2894. return new Ques(prev, POSSESSIVE);
  2895. }
  2896. return new Ques(prev, GREEDY);
  2897. case '*':
  2898. ch = next();
  2899. if (ch == '?') {
  2900. next();
  2901. return new Curly(prev, 0, MAX_REPS, LAZY);
  2902. } else if (ch == '+') {
  2903. next();
  2904. return new Curly(prev, 0, MAX_REPS, POSSESSIVE);
  2905. }
  2906. return new Curly(prev, 0, MAX_REPS, GREEDY);
  2907. case '+':
  2908. ch = next();
  2909. if (ch == '?') {
  2910. next();
  2911. return new Curly(prev, 1, MAX_REPS, LAZY);
  2912. } else if (ch == '+') {
  2913. next();
  2914. return new Curly(prev, 1, MAX_REPS, POSSESSIVE);
  2915. }
  2916. return new Curly(prev, 1, MAX_REPS, GREEDY);
  2917. case '{':
  2918. ch = temp[cursor+1];
  2919. if (ASCII.isDigit(ch)) {
  2920. skip();
  2921. int cmin = 0;
  2922. do {
  2923. cmin = cmin * 10 + (ch - '0');
  2924. } while (ASCII.isDigit(ch = read()));
  2925. int cmax = cmin;
  2926. if (ch == ',') {
  2927. ch = read();
  2928. cmax = MAX_REPS;
  2929. if (ch != '}') {
  2930. cmax = 0;
  2931. while (ASCII.isDigit(ch)) {
  2932. cmax = cmax * 10 + (ch - '0');
  2933. ch = read();
  2934. }
  2935. }
  2936. }
  2937. if (ch != '}')
  2938. throw error("Unclosed counted closure");
  2939. if (((cmin) | (cmax) | (cmax - cmin)) < 0)
  2940. throw error("Illegal repetition range");
  2941. Curly curly;
  2942. ch = peek();
  2943. if (ch == '?') {
  2944. next();
  2945. curly = new Curly(prev, cmin, cmax, LAZY);
  2946. } else if (ch == '+') {
  2947. next();
  2948. curly = new Curly(prev, cmin, cmax, POSSESSIVE);
  2949. } else {
  2950. curly = new Curly(prev, cmin, cmax, GREEDY);
  2951. }
  2952. return curly;
  2953. } else {
  2954. throw error("Illegal repetition");
  2955. }
  2956. default:
  2957. return prev;
  2958. }
  2959. }
  2960. /**
  2961. * Utility method for parsing control escape sequences.
  2962. */
  2963. private int c() {
  2964. if (cursor < patternLength) {
  2965. return read() ^ 64;
  2966. }
  2967. throw error("Illegal control escape sequence");
  2968. }
  2969. /**
  2970. * Utility method for parsing octal escape sequences.
  2971. */
  2972. private int o() {
  2973. int n = read();
  2974. if (((n-'0')|('7'-n)) >= 0) {
  2975. int m = read();
  2976. if (((m-'0')|('7'-m)) >= 0) {
  2977. int o = read();
  2978. if ((((o-'0')|('7'-o)) >= 0) && (((n-'0')|('3'-n)) >= 0)) {
  2979. return (n - '0') * 64 + (m - '0') * 8 + (o - '0');
  2980. }
  2981. unread();
  2982. return (n - '0') * 8 + (m - '0');
  2983. }
  2984. unread();
  2985. return (n - '0');
  2986. }
  2987. throw error("Illegal octal escape sequence");
  2988. }
  2989. /**
  2990. * Utility method for parsing hexadecimal escape sequences.
  2991. */
  2992. private int x() {
  2993. int n = read();
  2994. if (ASCII.isHexDigit(n)) {
  2995. int m = read();
  2996. if (ASCII.isHexDigit(m)) {
  2997. return ASCII.toDigit(n) * 16 + ASCII.toDigit(m);
  2998. }
  2999. } else if (n == '{' && ASCII.isHexDigit(peek())) {
  3000. int ch = 0;
  3001. while (ASCII.isHexDigit(n = read())) {
  3002. ch = (ch << 4) + ASCII.toDigit(n);
  3003. if (ch > Character.MAX_CODE_POINT)
  3004. throw error("Hexadecimal codepoint is too big");
  3005. }
  3006. if (n != '}')
  3007. throw error("Unclosed hexadecimal escape sequence");
  3008. return ch;
  3009. }
  3010. throw error("Illegal hexadecimal escape sequence");
  3011. }
  3012. /**
  3013. * Utility method for parsing unicode escape sequences.
  3014. */
  3015. private int cursor() {
  3016. return cursor;
  3017. }
  3018. private void setcursor(int pos) {
  3019. cursor = pos;
  3020. }
  3021. private int uxxxx() {
  3022. int n = 0;
  3023. for (int i = 0; i < 4; i++) {
  3024. int ch = read();
  3025. if (!ASCII.isHexDigit(ch)) {
  3026. throw error("Illegal Unicode escape sequence");
  3027. }
  3028. n = n * 16 + ASCII.toDigit(ch);
  3029. }
  3030. return n;
  3031. }
  3032. private int u() {
  3033. int n = uxxxx();
  3034. if (Character.isHighSurrogate((char)n)) {
  3035. int cur = cursor();
  3036. if (read() == '\\' && read() == 'u') {
  3037. int n2 = uxxxx();
  3038. if (Character.isLowSurrogate((char)n2))
  3039. return Character.toCodePoint((char)n, (char)n2);
  3040. }
  3041. setcursor(cur);
  3042. }
  3043. return n;
  3044. }
  3045. //
  3046. // Utility methods for code point support
  3047. //
  3048. private static final int countChars(CharSequence seq, int index,
  3049. int lengthInCodePoints) {
  3050. // optimization
  3051. if (lengthInCodePoints == 1 && !Character.isHighSurrogate(seq.charAt(index))) {
  3052. assert (index >= 0 && index < seq.length());
  3053. return 1;
  3054. }
  3055. int length = seq.length();
  3056. int x = index;
  3057. if (lengthInCodePoints >= 0) {
  3058. assert (index >= 0 && index < length);
  3059. for (int i = 0; x < length && i < lengthInCodePoints; i++) {
  3060. if (Character.isHighSurrogate(seq.charAt(x++))) {
  3061. if (x < length && Character.isLowSurrogate(seq.charAt(x))) {
  3062. x++;
  3063. }
  3064. }
  3065. }
  3066. return x - index;
  3067. }
  3068. assert (index >= 0 && index <= length);
  3069. if (index == 0) {
  3070. return 0;
  3071. }
  3072. int len = -lengthInCodePoints;
  3073. for (int i = 0; x > 0 && i < len; i++) {
  3074. if (Character.isLowSurrogate(seq.charAt(--x))) {
  3075. if (x > 0 && Character.isHighSurrogate(seq.charAt(x-1))) {
  3076. x--;
  3077. }
  3078. }
  3079. }
  3080. return index - x;
  3081. }
  3082. private static final int countCodePoints(CharSequence seq) {
  3083. int length = seq.length();
  3084. int n = 0;
  3085. for (int i = 0; i < length; ) {
  3086. n++;
  3087. if (Character.isHighSurrogate(seq.charAt(i++))) {
  3088. if (i < length && Character.isLowSurrogate(seq.charAt(i))) {
  3089. i++;
  3090. }
  3091. }
  3092. }
  3093. return n;
  3094. }
  3095. /**
  3096. * Creates a bit vector for matching Latin-1 values. A normal BitClass
  3097. * never matches values above Latin-1, and a complemented BitClass always
  3098. * matches values above Latin-1.
  3099. */
  3100. private static final class BitClass extends BmpCharProperty {
  3101. final boolean[] bits;
  3102. BitClass() { bits = new boolean[256]; }
  3103. private BitClass(boolean[] bits) { this.bits = bits; }
  3104. BitClass add(int c, int flags) {
  3105. assert c >= 0 && c <= 255;
  3106. if ((flags & CASE_INSENSITIVE) != 0) {
  3107. if (ASCII.isAscii(c)) {
  3108. bits[ASCII.toUpper(c)] = true;
  3109. bits[ASCII.toLower(c)] = true;
  3110. } else if ((flags & UNICODE_CASE) != 0) {
  3111. bits[Character.toLowerCase(c)] = true;
  3112. bits[Character.toUpperCase(c)] = true;
  3113. }
  3114. }
  3115. bits[c] = true;
  3116. return this;
  3117. }
  3118. boolean isSatisfiedBy(int ch) {
  3119. return ch < 256 && bits[ch];
  3120. }
  3121. }
  3122. /**
  3123. * Returns a suitably optimized, single character matcher.
  3124. */
  3125. private CharProperty newSingle(final int ch) {
  3126. if (has(CASE_INSENSITIVE)) {
  3127. int lower, upper;
  3128. if (has(UNICODE_CASE)) {
  3129. upper = Character.toUpperCase(ch);
  3130. lower = Character.toLowerCase(upper);
  3131. if (upper != lower)
  3132. return new SingleU(lower);
  3133. } else if (ASCII.isAscii(ch)) {
  3134. lower = ASCII.toLower(ch);
  3135. upper = ASCII.toUpper(ch);
  3136. if (lower != upper)
  3137. return new SingleI(lower, upper);
  3138. }
  3139. }
  3140. if (isSupplementary(ch))
  3141. return new SingleS(ch); // Match a given Unicode character
  3142. return new Single(ch); // Match a given BMP character
  3143. }
  3144. /**
  3145. * Utility method for creating a string slice matcher.
  3146. */
  3147. private Node newSlice(int[] buf, int count, boolean hasSupplementary) {
  3148. int[] tmp = new int[count];
  3149. if (has(CASE_INSENSITIVE)) {
  3150. if (has(UNICODE_CASE)) {
  3151. for (int i = 0; i < count; i++) {
  3152. tmp[i] = Character.toLowerCase(
  3153. Character.toUpperCase(buf[i]));
  3154. }
  3155. return hasSupplementary? new SliceUS(tmp) : new SliceU(tmp);
  3156. }
  3157. for (int i = 0; i < count; i++) {
  3158. tmp[i] = ASCII.toLower(buf[i]);
  3159. }
  3160. return hasSupplementary? new SliceIS(tmp) : new SliceI(tmp);
  3161. }
  3162. for (int i = 0; i < count; i++) {
  3163. tmp[i] = buf[i];
  3164. }
  3165. return hasSupplementary ? new SliceS(tmp) : new Slice(tmp);
  3166. }
  3167. /**
  3168. * The following classes are the building components of the object
  3169. * tree that represents a compiled regular expression. The object tree
  3170. * is made of individual elements that handle constructs in the Pattern.
  3171. * Each type of object knows how to match its equivalent construct with
  3172. * the match() method.
  3173. */
  3174. /**
  3175. * Base class for all node classes. Subclasses should override the match()
  3176. * method as appropriate. This class is an accepting node, so its match()
  3177. * always returns true.
  3178. */
  3179. static class Node extends Object {
  3180. Node next;
  3181. Node() {
  3182. next = Pattern.accept;
  3183. }
  3184. /**
  3185. * This method implements the classic accept node.
  3186. */
  3187. boolean match(Matcher matcher, int i, CharSequence seq) {
  3188. matcher.last = i;
  3189. matcher.groups[0] = matcher.first;
  3190. matcher.groups[1] = matcher.last;
  3191. return true;
  3192. }
  3193. /**
  3194. * This method is good for all zero length assertions.
  3195. */
  3196. boolean study(TreeInfo info) {
  3197. if (next != null) {
  3198. return next.study(info);
  3199. } else {
  3200. return info.deterministic;
  3201. }
  3202. }
  3203. }
  3204. static class LastNode extends Node {
  3205. /**
  3206. * This method implements the classic accept node with
  3207. * the addition of a check to see if the match occurred
  3208. * using all of the input.
  3209. */
  3210. boolean match(Matcher matcher, int i, CharSequence seq) {
  3211. if (matcher.acceptMode == Matcher.ENDANCHOR && i != matcher.to)
  3212. return false;
  3213. matcher.last = i;
  3214. matcher.groups[0] = matcher.first;
  3215. matcher.groups[1] = matcher.last;
  3216. return true;
  3217. }
  3218. }
  3219. /**
  3220. * Used for REs that can start anywhere within the input string.
  3221. * This basically tries to match repeatedly at each spot in the
  3222. * input string, moving forward after each try. An anchored search
  3223. * or a BnM will bypass this node completely.
  3224. */
  3225. static class Start extends Node {
  3226. int minLength;
  3227. Start(Node node) {
  3228. this.next = node;
  3229. TreeInfo info = new TreeInfo();
  3230. next.study(info);
  3231. minLength = info.minLength;
  3232. }
  3233. boolean match(Matcher matcher, int i, CharSequence seq) {
  3234. if (i > matcher.to - minLength) {
  3235. matcher.hitEnd = true;
  3236. return false;
  3237. }
  3238. int guard = matcher.to - minLength;
  3239. for (; i <= guard; i++) {
  3240. if (next.match(matcher, i, seq)) {
  3241. matcher.first = i;
  3242. matcher.groups[0] = matcher.first;
  3243. matcher.groups[1] = matcher.last;
  3244. return true;
  3245. }
  3246. }
  3247. matcher.hitEnd = true;
  3248. return false;
  3249. }
  3250. boolean study(TreeInfo info) {
  3251. next.study(info);
  3252. info.maxValid = false;
  3253. info.deterministic = false;
  3254. return false;
  3255. }
  3256. }
  3257. /*
  3258. * StartS supports supplementary characters, including unpaired surrogates.
  3259. */
  3260. static final class StartS extends Start {
  3261. StartS(Node node) {
  3262. super(node);
  3263. }
  3264. boolean match(Matcher matcher, int i, CharSequence seq) {
  3265. if (i > matcher.to - minLength) {
  3266. matcher.hitEnd = true;
  3267. return false;
  3268. }
  3269. int guard = matcher.to - minLength;
  3270. while (i <= guard) {
  3271. //if ((ret = next.match(matcher, i, seq)) || i == guard)
  3272. if (next.match(matcher, i, seq)) {
  3273. matcher.first = i;
  3274. matcher.groups[0] = matcher.first;
  3275. matcher.groups[1] = matcher.last;
  3276. return true;
  3277. }
  3278. if (i == guard)
  3279. break;
  3280. // Optimization to move to the next character. This is
  3281. // faster than countChars(seq, i, 1).
  3282. if (Character.isHighSurrogate(seq.charAt(i++))) {
  3283. if (i < seq.length() &&
  3284. Character.isLowSurrogate(seq.charAt(i))) {
  3285. i++;
  3286. }
  3287. }
  3288. }
  3289. matcher.hitEnd = true;
  3290. return false;
  3291. }
  3292. }
  3293. /**
  3294. * Node to anchor at the beginning of input. This object implements the
  3295. * match for a \A sequence, and the caret anchor will use this if not in
  3296. * multiline mode.
  3297. */
  3298. static final class Begin extends Node {
  3299. boolean match(Matcher matcher, int i, CharSequence seq) {
  3300. int fromIndex = (matcher.anchoringBounds) ?
  3301. matcher.from : 0;
  3302. if (i == fromIndex && next.match(matcher, i, seq)) {
  3303. matcher.first = i;
  3304. matcher.groups[0] = i;
  3305. matcher.groups[1] = matcher.last;
  3306. return true;
  3307. } else {
  3308. return false;
  3309. }
  3310. }
  3311. }
  3312. /**
  3313. * Node to anchor at the end of input. This is the absolute end, so this
  3314. * should not match at the last newline before the end as $ will.
  3315. */
  3316. static final class End extends Node {
  3317. boolean match(Matcher matcher, int i, CharSequence seq) {
  3318. int endIndex = (matcher.anchoringBounds) ?
  3319. matcher.to : matcher.getTextLength();
  3320. if (i == endIndex) {
  3321. matcher.hitEnd = true;
  3322. return next.match(matcher, i, seq);
  3323. }
  3324. return false;
  3325. }
  3326. }
  3327. /**
  3328. * Node to anchor at the beginning of a line. This is essentially the
  3329. * object to match for the multiline ^.
  3330. */
  3331. static final class Caret extends Node {
  3332. boolean match(Matcher matcher, int i, CharSequence seq) {
  3333. int startIndex = matcher.from;
  3334. int endIndex = matcher.to;
  3335. if (!matcher.anchoringBounds) {
  3336. startIndex = 0;
  3337. endIndex = matcher.getTextLength();
  3338. }
  3339. // Perl does not match ^ at end of input even after newline
  3340. if (i == endIndex) {
  3341. matcher.hitEnd = true;
  3342. return false;
  3343. }
  3344. if (i > startIndex) {
  3345. char ch = seq.charAt(i-1);
  3346. if (ch != '\n' && ch != '\r'
  3347. && (ch|1) != '\u2029'
  3348. && ch != '\u0085' ) {
  3349. return false;
  3350. }
  3351. // Should treat /r/n as one newline
  3352. if (ch == '\r' && seq.charAt(i) == '\n')
  3353. return false;
  3354. }
  3355. return next.match(matcher, i, seq);
  3356. }
  3357. }
  3358. /**
  3359. * Node to anchor at the beginning of a line when in unixdot mode.
  3360. */
  3361. static final class UnixCaret extends Node {
  3362. boolean match(Matcher matcher, int i, CharSequence seq) {
  3363. int startIndex = matcher.from;
  3364. int endIndex = matcher.to;
  3365. if (!matcher.anchoringBounds) {
  3366. startIndex = 0;
  3367. endIndex = matcher.getTextLength();
  3368. }
  3369. // Perl does not match ^ at end of input even after newline
  3370. if (i == endIndex) {
  3371. matcher.hitEnd = true;
  3372. return false;
  3373. }
  3374. if (i > startIndex) {
  3375. char ch = seq.charAt(i-1);
  3376. if (ch != '\n') {
  3377. return false;
  3378. }
  3379. }
  3380. return next.match(matcher, i, seq);
  3381. }
  3382. }
  3383. /**
  3384. * Node to match the location where the last match ended.
  3385. * This is used for the \G construct.
  3386. */
  3387. static final class LastMatch extends Node {
  3388. boolean match(Matcher matcher, int i, CharSequence seq) {
  3389. if (i != matcher.oldLast)
  3390. return false;
  3391. return next.match(matcher, i, seq);
  3392. }
  3393. }
  3394. /**
  3395. * Node to anchor at the end of a line or the end of input based on the
  3396. * multiline mode.
  3397. *
  3398. * When not in multiline mode, the $ can only match at the very end
  3399. * of the input, unless the input ends in a line terminator in which
  3400. * it matches right before the last line terminator.
  3401. *
  3402. * Note that \r\n is considered an atomic line terminator.
  3403. *
  3404. * Like ^ the $ operator matches at a position, it does not match the
  3405. * line terminators themselves.
  3406. */
  3407. static final class Dollar extends Node {
  3408. boolean multiline;
  3409. Dollar(boolean mul) {
  3410. multiline = mul;
  3411. }
  3412. boolean match(Matcher matcher, int i, CharSequence seq) {
  3413. int endIndex = (matcher.anchoringBounds) ?
  3414. matcher.to : matcher.getTextLength();
  3415. if (!multiline) {
  3416. if (i < endIndex - 2)
  3417. return false;
  3418. if (i == endIndex - 2) {
  3419. char ch = seq.charAt(i);
  3420. if (ch != '\r')
  3421. return false;
  3422. ch = seq.charAt(i + 1);
  3423. if (ch != '\n')
  3424. return false;
  3425. }
  3426. }
  3427. // Matches before any line terminator; also matches at the
  3428. // end of input
  3429. // Before line terminator:
  3430. // If multiline, we match here no matter what
  3431. // If not multiline, fall through so that the end
  3432. // is marked as hit; this must be a /r/n or a /n
  3433. // at the very end so the end was hit; more input
  3434. // could make this not match here
  3435. if (i < endIndex) {
  3436. char ch = seq.charAt(i);
  3437. if (ch == '\n') {
  3438. // No match between \r\n
  3439. if (i > 0 && seq.charAt(i-1) == '\r')
  3440. return false;
  3441. if (multiline)
  3442. return next.match(matcher, i, seq);
  3443. } else if (ch == '\r' || ch == '\u0085' ||
  3444. (ch|1) == '\u2029') {
  3445. if (multiline)
  3446. return next.match(matcher, i, seq);
  3447. } else { // No line terminator, no match
  3448. return false;
  3449. }
  3450. }
  3451. // Matched at current end so hit end
  3452. matcher.hitEnd = true;
  3453. // If a $ matches because of end of input, then more input
  3454. // could cause it to fail!
  3455. matcher.requireEnd = true;
  3456. return next.match(matcher, i, seq);
  3457. }
  3458. boolean study(TreeInfo info) {
  3459. next.study(info);
  3460. return info.deterministic;
  3461. }
  3462. }
  3463. /**
  3464. * Node to anchor at the end of a line or the end of input based on the
  3465. * multiline mode when in unix lines mode.
  3466. */
  3467. static final class UnixDollar extends Node {
  3468. boolean multiline;
  3469. UnixDollar(boolean mul) {
  3470. multiline = mul;
  3471. }
  3472. boolean match(Matcher matcher, int i, CharSequence seq) {
  3473. int endIndex = (matcher.anchoringBounds) ?
  3474. matcher.to : matcher.getTextLength();
  3475. if (i < endIndex) {
  3476. char ch = seq.charAt(i);
  3477. if (ch == '\n') {
  3478. // If not multiline, then only possible to
  3479. // match at very end or one before end
  3480. if (multiline == false && i != endIndex - 1)
  3481. return false;
  3482. // If multiline return next.match without setting
  3483. // matcher.hitEnd
  3484. if (multiline)
  3485. return next.match(matcher, i, seq);
  3486. } else {
  3487. return false;
  3488. }
  3489. }
  3490. // Matching because at the end or 1 before the end;
  3491. // more input could change this so set hitEnd
  3492. matcher.hitEnd = true;
  3493. // If a $ matches because of end of input, then more input
  3494. // could cause it to fail!
  3495. matcher.requireEnd = true;
  3496. return next.match(matcher, i, seq);
  3497. }
  3498. boolean study(TreeInfo info) {
  3499. next.study(info);
  3500. return info.deterministic;
  3501. }
  3502. }
  3503. /**
  3504. * Abstract node class to match one character satisfying some
  3505. * boolean property.
  3506. */
  3507. private static abstract class CharProperty extends Node {
  3508. abstract boolean isSatisfiedBy(int ch);
  3509. CharProperty complement() {
  3510. return new CharProperty() {
  3511. boolean isSatisfiedBy(int ch) {
  3512. return ! CharProperty.this.isSatisfiedBy(ch);}};
  3513. }
  3514. boolean match(Matcher matcher, int i, CharSequence seq) {
  3515. if (i < matcher.to) {
  3516. int ch = Character.codePointAt(seq, i);
  3517. return isSatisfiedBy(ch)
  3518. && next.match(matcher, i+Character.charCount(ch), seq);
  3519. } else {
  3520. matcher.hitEnd = true;
  3521. return false;
  3522. }
  3523. }
  3524. boolean study(TreeInfo info) {
  3525. info.minLength++;
  3526. info.maxLength++;
  3527. return next.study(info);
  3528. }
  3529. }
  3530. /**
  3531. * Optimized version of CharProperty that works only for
  3532. * properties never satisfied by Supplementary characters.
  3533. */
  3534. private static abstract class BmpCharProperty extends CharProperty {
  3535. boolean match(Matcher matcher, int i, CharSequence seq) {
  3536. if (i < matcher.to) {
  3537. return isSatisfiedBy(seq.charAt(i))
  3538. && next.match(matcher, i+1, seq);
  3539. } else {
  3540. matcher.hitEnd = true;
  3541. return false;
  3542. }
  3543. }
  3544. }
  3545. /**
  3546. * Node class that matches a Supplementary Unicode character
  3547. */
  3548. static final class SingleS extends CharProperty {
  3549. final int c;
  3550. SingleS(int c) { this.c = c; }
  3551. boolean isSatisfiedBy(int ch) {
  3552. return ch == c;
  3553. }
  3554. }
  3555. /**
  3556. * Optimization -- matches a given BMP character
  3557. */
  3558. static final class Single extends BmpCharProperty {
  3559. final int c;
  3560. Single(int c) { this.c = c; }
  3561. boolean isSatisfiedBy(int ch) {
  3562. return ch == c;
  3563. }
  3564. }
  3565. /**
  3566. * Case insensitive matches a given BMP character
  3567. */
  3568. static final class SingleI extends BmpCharProperty {
  3569. final int lower;
  3570. final int upper;
  3571. SingleI(int lower, int upper) {
  3572. this.lower = lower;
  3573. this.upper = upper;
  3574. }
  3575. boolean isSatisfiedBy(int ch) {
  3576. return ch == lower || ch == upper;
  3577. }
  3578. }
  3579. /**
  3580. * Unicode case insensitive matches a given Unicode character
  3581. */
  3582. static final class SingleU extends CharProperty {
  3583. final int lower;
  3584. SingleU(int lower) {
  3585. this.lower = lower;
  3586. }
  3587. boolean isSatisfiedBy(int ch) {
  3588. return lower == ch ||
  3589. lower == Character.toLowerCase(Character.toUpperCase(ch));
  3590. }
  3591. }
  3592. /**
  3593. * Node class that matches a Unicode block.
  3594. */
  3595. static final class Block extends CharProperty {
  3596. final Character.UnicodeBlock block;
  3597. Block(Character.UnicodeBlock block) {
  3598. this.block = block;
  3599. }
  3600. boolean isSatisfiedBy(int ch) {
  3601. return block == Character.UnicodeBlock.of(ch);
  3602. }
  3603. }
  3604. /**
  3605. * Node class that matches a Unicode script
  3606. */
  3607. static final class Script extends CharProperty {
  3608. final Character.UnicodeScript script;
  3609. Script(Character.UnicodeScript script) {
  3610. this.script = script;
  3611. }
  3612. boolean isSatisfiedBy(int ch) {
  3613. return script == Character.UnicodeScript.of(ch);
  3614. }
  3615. }
  3616. /**
  3617. * Node class that matches a Unicode category.
  3618. */
  3619. static final class Category extends CharProperty {
  3620. final int typeMask;
  3621. Category(int typeMask) { this.typeMask = typeMask; }
  3622. boolean isSatisfiedBy(int ch) {
  3623. return (typeMask & (1 << Character.getType(ch))) != 0;
  3624. }
  3625. }
  3626. /**
  3627. * Node class that matches a Unicode "type"
  3628. */
  3629. static final class Utype extends CharProperty {
  3630. final UnicodeProp uprop;
  3631. Utype(UnicodeProp uprop) { this.uprop = uprop; }
  3632. boolean isSatisfiedBy(int ch) {
  3633. return uprop.is(ch);
  3634. }
  3635. }
  3636. /**
  3637. * Node class that matches a POSIX type.
  3638. */
  3639. static final class Ctype extends BmpCharProperty {
  3640. final int ctype;
  3641. Ctype(int ctype) { this.ctype = ctype; }
  3642. boolean isSatisfiedBy(int ch) {
  3643. return ch < 128 && ASCII.isType(ch, ctype);
  3644. }
  3645. }
  3646. /**
  3647. * Base class for all Slice nodes
  3648. */
  3649. static class SliceNode extends Node {
  3650. int[] buffer;
  3651. SliceNode(int[] buf) {
  3652. buffer = buf;
  3653. }
  3654. boolean study(TreeInfo info) {
  3655. info.minLength += buffer.length;
  3656. info.maxLength += buffer.length;
  3657. return next.study(info);
  3658. }
  3659. }
  3660. /**
  3661. * Node class for a case sensitive/BMP-only sequence of literal
  3662. * characters.
  3663. */
  3664. static final class Slice extends SliceNode {
  3665. Slice(int[] buf) {
  3666. super(buf);
  3667. }
  3668. boolean match(Matcher matcher, int i, CharSequence seq) {
  3669. int[] buf = buffer;
  3670. int len = buf.length;
  3671. for (int j=0; j<len; j++) {
  3672. if ((i+j) >= matcher.to) {
  3673. matcher.hitEnd = true;
  3674. return false;
  3675. }
  3676. if (buf[j] != seq.charAt(i+j))
  3677. return false;
  3678. }
  3679. return next.match(matcher, i+len, seq);
  3680. }
  3681. }
  3682. /**
  3683. * Node class for a case_insensitive/BMP-only sequence of literal
  3684. * characters.
  3685. */
  3686. static class SliceI extends SliceNode {
  3687. SliceI(int[] buf) {
  3688. super(buf);
  3689. }
  3690. boolean match(Matcher matcher, int i, CharSequence seq) {
  3691. int[] buf = buffer;
  3692. int len = buf.length;
  3693. for (int j=0; j<len; j++) {
  3694. if ((i+j) >= matcher.to) {
  3695. matcher.hitEnd = true;
  3696. return false;
  3697. }
  3698. int c = seq.charAt(i+j);
  3699. if (buf[j] != c &&
  3700. buf[j] != ASCII.toLower(c))
  3701. return false;
  3702. }
  3703. return next.match(matcher, i+len, seq);
  3704. }
  3705. }
  3706. /**
  3707. * Node class for a unicode_case_insensitive/BMP-only sequence of
  3708. * literal characters. Uses unicode case folding.
  3709. */
  3710. static final class SliceU extends SliceNode {
  3711. SliceU(int[] buf) {
  3712. super(buf);
  3713. }
  3714. boolean match(Matcher matcher, int i, CharSequence seq) {
  3715. int[] buf = buffer;
  3716. int len = buf.length;
  3717. for (int j=0; j<len; j++) {
  3718. if ((i+j) >= matcher.to) {
  3719. matcher.hitEnd = true;
  3720. return false;
  3721. }
  3722. int c = seq.charAt(i+j);
  3723. if (buf[j] != c &&
  3724. buf[j] != Character.toLowerCase(Character.toUpperCase(c)))
  3725. return false;
  3726. }
  3727. return next.match(matcher, i+len, seq);
  3728. }
  3729. }
  3730. /**
  3731. * Node class for a case sensitive sequence of literal characters
  3732. * including supplementary characters.
  3733. */
  3734. static final class SliceS extends SliceNode {
  3735. SliceS(int[] buf) {
  3736. super(buf);
  3737. }
  3738. boolean match(Matcher matcher, int i, CharSequence seq) {
  3739. int[] buf = buffer;
  3740. int x = i;
  3741. for (int j = 0; j < buf.length; j++) {
  3742. if (x >= matcher.to) {
  3743. matcher.hitEnd = true;
  3744. return false;
  3745. }
  3746. int c = Character.codePointAt(seq, x);
  3747. if (buf[j] != c)
  3748. return false;
  3749. x += Character.charCount(c);
  3750. if (x > matcher.to) {
  3751. matcher.hitEnd = true;
  3752. return false;
  3753. }
  3754. }
  3755. return next.match(matcher, x, seq);
  3756. }
  3757. }
  3758. /**
  3759. * Node class for a case insensitive sequence of literal characters
  3760. * including supplementary characters.
  3761. */
  3762. static class SliceIS extends SliceNode {
  3763. SliceIS(int[] buf) {
  3764. super(buf);
  3765. }
  3766. int toLower(int c) {
  3767. return ASCII.toLower(c);
  3768. }
  3769. boolean match(Matcher matcher, int i, CharSequence seq) {
  3770. int[] buf = buffer;
  3771. int x = i;
  3772. for (int j = 0; j < buf.length; j++) {
  3773. if (x >= matcher.to) {
  3774. matcher.hitEnd = true;
  3775. return false;
  3776. }
  3777. int c = Character.codePointAt(seq, x);
  3778. if (buf[j] != c && buf[j] != toLower(c))
  3779. return false;
  3780. x += Character.charCount(c);
  3781. if (x > matcher.to) {
  3782. matcher.hitEnd = true;
  3783. return false;
  3784. }
  3785. }
  3786. return next.match(matcher, x, seq);
  3787. }
  3788. }
  3789. /**
  3790. * Node class for a case insensitive sequence of literal characters.
  3791. * Uses unicode case folding.
  3792. */
  3793. static final class SliceUS extends SliceIS {
  3794. SliceUS(int[] buf) {
  3795. super(buf);
  3796. }
  3797. int toLower(int c) {
  3798. return Character.toLowerCase(Character.toUpperCase(c));
  3799. }
  3800. }
  3801. private static boolean inRange(int lower, int ch, int upper) {
  3802. return lower <= ch && ch <= upper;
  3803. }
  3804. /**
  3805. * Returns node for matching characters within an explicit value range.
  3806. */
  3807. private static CharProperty rangeFor(final int lower,
  3808. final int upper) {
  3809. return new CharProperty() {
  3810. boolean isSatisfiedBy(int ch) {
  3811. return inRange(lower, ch, upper);}};
  3812. }
  3813. /**
  3814. * Returns node for matching characters within an explicit value
  3815. * range in a case insensitive manner.
  3816. */
  3817. private CharProperty caseInsensitiveRangeFor(final int lower,
  3818. final int upper) {
  3819. if (has(UNICODE_CASE))
  3820. return new CharProperty() {
  3821. boolean isSatisfiedBy(int ch) {
  3822. if (inRange(lower, ch, upper))
  3823. return true;
  3824. int up = Character.toUpperCase(ch);
  3825. return inRange(lower, up, upper) ||
  3826. inRange(lower, Character.toLowerCase(up), upper);}};
  3827. return new CharProperty() {
  3828. boolean isSatisfiedBy(int ch) {
  3829. return inRange(lower, ch, upper) ||
  3830. ASCII.isAscii(ch) &&
  3831. (inRange(lower, ASCII.toUpper(ch), upper) ||
  3832. inRange(lower, ASCII.toLower(ch), upper));
  3833. }};
  3834. }
  3835. /**
  3836. * Implements the Unicode category ALL and the dot metacharacter when
  3837. * in dotall mode.
  3838. */
  3839. static final class All extends CharProperty {
  3840. boolean isSatisfiedBy(int ch) {
  3841. return true;
  3842. }
  3843. }
  3844. /**
  3845. * Node class for the dot metacharacter when dotall is not enabled.
  3846. */
  3847. static final class Dot extends CharProperty {
  3848. boolean isSatisfiedBy(int ch) {
  3849. return (ch != '\n' && ch != '\r'
  3850. && (ch|1) != '\u2029'
  3851. && ch != '\u0085');
  3852. }
  3853. }
  3854. /**
  3855. * Node class for the dot metacharacter when dotall is not enabled
  3856. * but UNIX_LINES is enabled.
  3857. */
  3858. static final class UnixDot extends CharProperty {
  3859. boolean isSatisfiedBy(int ch) {
  3860. return ch != '\n';
  3861. }
  3862. }
  3863. /**
  3864. * The 0 or 1 quantifier. This one class implements all three types.
  3865. */
  3866. static final class Ques extends Node {
  3867. Node atom;
  3868. int type;
  3869. Ques(Node node, int type) {
  3870. this.atom = node;
  3871. this.type = type;
  3872. }
  3873. boolean match(Matcher matcher, int i, CharSequence seq) {
  3874. switch (type) {
  3875. case GREEDY:
  3876. return (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq))
  3877. || next.match(matcher, i, seq);
  3878. case LAZY:
  3879. return next.match(matcher, i, seq)
  3880. || (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq));
  3881. case POSSESSIVE:
  3882. if (atom.match(matcher, i, seq)) i = matcher.last;
  3883. return next.match(matcher, i, seq);
  3884. default:
  3885. return atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq);
  3886. }
  3887. }
  3888. boolean study(TreeInfo info) {
  3889. if (type != INDEPENDENT) {
  3890. int minL = info.minLength;
  3891. atom.study(info);
  3892. info.minLength = minL;
  3893. info.deterministic = false;
  3894. return next.study(info);
  3895. } else {
  3896. atom.study(info);
  3897. return next.study(info);
  3898. }
  3899. }
  3900. }
  3901. /**
  3902. * Handles the curly-brace style repetition with a specified minimum and
  3903. * maximum occurrences. The * quantifier is handled as a special case.
  3904. * This class handles the three types.
  3905. */
  3906. static final class Curly extends Node {
  3907. Node atom;
  3908. int type;
  3909. int cmin;
  3910. int cmax;
  3911. Curly(Node node, int cmin, int cmax, int type) {
  3912. this.atom = node;
  3913. this.type = type;
  3914. this.cmin = cmin;
  3915. this.cmax = cmax;
  3916. }
  3917. boolean match(Matcher matcher, int i, CharSequence seq) {
  3918. int j;
  3919. for (j = 0; j < cmin; j++) {
  3920. if (atom.match(matcher, i, seq)) {
  3921. i = matcher.last;
  3922. continue;
  3923. }
  3924. return false;
  3925. }
  3926. if (type == GREEDY)
  3927. return match0(matcher, i, j, seq);
  3928. else if (type == LAZY)
  3929. return match1(matcher, i, j, seq);
  3930. else
  3931. return match2(matcher, i, j, seq);
  3932. }
  3933. // Greedy match.
  3934. // i is the index to start matching at
  3935. // j is the number of atoms that have matched
  3936. boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
  3937. if (j >= cmax) {
  3938. // We have matched the maximum... continue with the rest of
  3939. // the regular expression
  3940. return next.match(matcher, i, seq);
  3941. }
  3942. int backLimit = j;
  3943. while (atom.match(matcher, i, seq)) {
  3944. // k is the length of this match
  3945. int k = matcher.last - i;
  3946. if (k == 0) // Zero length match
  3947. break;
  3948. // Move up index and number matched
  3949. i = matcher.last;
  3950. j++;
  3951. // We are greedy so match as many as we can
  3952. while (j < cmax) {
  3953. if (!atom.match(matcher, i, seq))
  3954. break;
  3955. if (i + k != matcher.last) {
  3956. if (match0(matcher, matcher.last, j+1, seq))
  3957. return true;
  3958. break;
  3959. }
  3960. i += k;
  3961. j++;
  3962. }
  3963. // Handle backing off if match fails
  3964. while (j >= backLimit) {
  3965. if (next.match(matcher, i, seq))
  3966. return true;
  3967. i -= k;
  3968. j--;
  3969. }
  3970. return false;
  3971. }
  3972. return next.match(matcher, i, seq);
  3973. }
  3974. // Reluctant match. At this point, the minimum has been satisfied.
  3975. // i is the index to start matching at
  3976. // j is the number of atoms that have matched
  3977. boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
  3978. for (;;) {
  3979. // Try finishing match without consuming any more
  3980. if (next.match(matcher, i, seq))
  3981. return true;
  3982. // At the maximum, no match found
  3983. if (j >= cmax)
  3984. return false;
  3985. // Okay, must try one more atom
  3986. if (!atom.match(matcher, i, seq))
  3987. return false;
  3988. // If we haven't moved forward then must break out
  3989. if (i == matcher.last)
  3990. return false;
  3991. // Move up index and number matched
  3992. i = matcher.last;
  3993. j++;
  3994. }
  3995. }
  3996. boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
  3997. for (; j < cmax; j++) {
  3998. if (!atom.match(matcher, i, seq))
  3999. break;
  4000. if (i == matcher.last)
  4001. break;
  4002. i = matcher.last;
  4003. }
  4004. return next.match(matcher, i, seq);
  4005. }
  4006. boolean study(TreeInfo info) {
  4007. // Save original info
  4008. int minL = info.minLength;
  4009. int maxL = info.maxLength;
  4010. boolean maxV = info.maxValid;
  4011. boolean detm = info.deterministic;
  4012. info.reset();
  4013. atom.study(info);
  4014. int temp = info.minLength * cmin + minL;
  4015. if (temp < minL) {
  4016. temp = 0xFFFFFFF; // arbitrary large number
  4017. }
  4018. info.minLength = temp;
  4019. if (maxV & info.maxValid) {
  4020. temp = info.maxLength * cmax + maxL;
  4021. info.maxLength = temp;
  4022. if (temp < maxL) {
  4023. info.maxValid = false;
  4024. }
  4025. } else {
  4026. info.maxValid = false;
  4027. }
  4028. if (info.deterministic && cmin == cmax)
  4029. info.deterministic = detm;
  4030. else
  4031. info.deterministic = false;
  4032. return next.study(info);
  4033. }
  4034. }
  4035. /**
  4036. * Handles the curly-brace style repetition with a specified minimum and
  4037. * maximum occurrences in deterministic cases. This is an iterative
  4038. * optimization over the Prolog and Loop system which would handle this
  4039. * in a recursive way. The * quantifier is handled as a special case.
  4040. * If capture is true then this class saves group settings and ensures
  4041. * that groups are unset when backing off of a group match.
  4042. */
  4043. static final class GroupCurly extends Node {
  4044. Node atom;
  4045. int type;
  4046. int cmin;
  4047. int cmax;
  4048. int localIndex;
  4049. int groupIndex;
  4050. boolean capture;
  4051. GroupCurly(Node node, int cmin, int cmax, int type, int local,
  4052. int group, boolean capture) {
  4053. this.atom = node;
  4054. this.type = type;
  4055. this.cmin = cmin;
  4056. this.cmax = cmax;
  4057. this.localIndex = local;
  4058. this.groupIndex = group;
  4059. this.capture = capture;
  4060. }
  4061. boolean match(Matcher matcher, int i, CharSequence seq) {
  4062. int[] groups = matcher.groups;
  4063. int[] locals = matcher.locals;
  4064. int save0 = locals[localIndex];
  4065. int save1 = 0;
  4066. int save2 = 0;
  4067. if (capture) {
  4068. save1 = groups[groupIndex];
  4069. save2 = groups[groupIndex+1];
  4070. }
  4071. // Notify GroupTail there is no need to setup group info
  4072. // because it will be set here
  4073. locals[localIndex] = -1;
  4074. boolean ret = true;
  4075. for (int j = 0; j < cmin; j++) {
  4076. if (atom.match(matcher, i, seq)) {
  4077. if (capture) {
  4078. groups[groupIndex] = i;
  4079. groups[groupIndex+1] = matcher.last;
  4080. }
  4081. i = matcher.last;
  4082. } else {
  4083. ret = false;
  4084. break;
  4085. }
  4086. }
  4087. if (ret) {
  4088. if (type == GREEDY) {
  4089. ret = match0(matcher, i, cmin, seq);
  4090. } else if (type == LAZY) {
  4091. ret = match1(matcher, i, cmin, seq);
  4092. } else {
  4093. ret = match2(matcher, i, cmin, seq);
  4094. }
  4095. }
  4096. if (!ret) {
  4097. locals[localIndex] = save0;
  4098. if (capture) {
  4099. groups[groupIndex] = save1;
  4100. groups[groupIndex+1] = save2;
  4101. }
  4102. }
  4103. return ret;
  4104. }
  4105. // Aggressive group match
  4106. boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
  4107. int[] groups = matcher.groups;
  4108. int save0 = 0;
  4109. int save1 = 0;
  4110. if (capture) {
  4111. save0 = groups[groupIndex];
  4112. save1 = groups[groupIndex+1];
  4113. }
  4114. for (;;) {
  4115. if (j >= cmax)
  4116. break;
  4117. if (!atom.match(matcher, i, seq))
  4118. break;
  4119. int k = matcher.last - i;
  4120. if (k <= 0) {
  4121. if (capture) {
  4122. groups[groupIndex] = i;
  4123. groups[groupIndex+1] = i + k;
  4124. }
  4125. i = i + k;
  4126. break;
  4127. }
  4128. for (;;) {
  4129. if (capture) {
  4130. groups[groupIndex] = i;
  4131. groups[groupIndex+1] = i + k;
  4132. }
  4133. i = i + k;
  4134. if (++j >= cmax)
  4135. break;
  4136. if (!atom.match(matcher, i, seq))
  4137. break;
  4138. if (i + k != matcher.last) {
  4139. if (match0(matcher, i, j, seq))
  4140. return true;
  4141. break;
  4142. }
  4143. }
  4144. while (j > cmin) {
  4145. if (next.match(matcher, i, seq)) {
  4146. if (capture) {
  4147. groups[groupIndex+1] = i;
  4148. groups[groupIndex] = i - k;
  4149. }
  4150. i = i - k;
  4151. return true;
  4152. }
  4153. // backing off
  4154. if (capture) {
  4155. groups[groupIndex+1] = i;
  4156. groups[groupIndex] = i - k;
  4157. }
  4158. i = i - k;
  4159. j--;
  4160. }
  4161. break;
  4162. }
  4163. if (capture) {
  4164. groups[groupIndex] = save0;
  4165. groups[groupIndex+1] = save1;
  4166. }
  4167. return next.match(matcher, i, seq);
  4168. }
  4169. // Reluctant matching
  4170. boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
  4171. for (;;) {
  4172. if (next.match(matcher, i, seq))
  4173. return true;
  4174. if (j >= cmax)
  4175. return false;
  4176. if (!atom.match(matcher, i, seq))
  4177. return false;
  4178. if (i == matcher.last)
  4179. return false;
  4180. if (capture) {
  4181. matcher.groups[groupIndex] = i;
  4182. matcher.groups[groupIndex+1] = matcher.last;
  4183. }
  4184. i = matcher.last;
  4185. j++;
  4186. }
  4187. }
  4188. // Possessive matching
  4189. boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
  4190. for (; j < cmax; j++) {
  4191. if (!atom.match(matcher, i, seq)) {
  4192. break;
  4193. }
  4194. if (capture) {
  4195. matcher.groups[groupIndex] = i;
  4196. matcher.groups[groupIndex+1] = matcher.last;
  4197. }
  4198. if (i == matcher.last) {
  4199. break;
  4200. }
  4201. i = matcher.last;
  4202. }
  4203. return next.match(matcher, i, seq);
  4204. }
  4205. boolean study(TreeInfo info) {
  4206. // Save original info
  4207. int minL = info.minLength;
  4208. int maxL = info.maxLength;
  4209. boolean maxV = info.maxValid;
  4210. boolean detm = info.deterministic;
  4211. info.reset();
  4212. atom.study(info);
  4213. int temp = info.minLength * cmin + minL;
  4214. if (temp < minL) {
  4215. temp = 0xFFFFFFF; // Arbitrary large number
  4216. }
  4217. info.minLength = temp;
  4218. if (maxV & info.maxValid) {
  4219. temp = info.maxLength * cmax + maxL;
  4220. info.maxLength = temp;
  4221. if (temp < maxL) {
  4222. info.maxValid = false;
  4223. }
  4224. } else {
  4225. info.maxValid = false;
  4226. }
  4227. if (info.deterministic && cmin == cmax) {
  4228. info.deterministic = detm;
  4229. } else {
  4230. info.deterministic = false;
  4231. }
  4232. return next.study(info);
  4233. }
  4234. }
  4235. /**
  4236. * A Guard node at the end of each atom node in a Branch. It
  4237. * serves the purpose of chaining the "match" operation to
  4238. * "next" but not the "study", so we can collect the TreeInfo
  4239. * of each atom node without including the TreeInfo of the
  4240. * "next".
  4241. */
  4242. static final class BranchConn extends Node {
  4243. BranchConn() {};
  4244. boolean match(Matcher matcher, int i, CharSequence seq) {
  4245. return next.match(matcher, i, seq);
  4246. }
  4247. boolean study(TreeInfo info) {
  4248. return info.deterministic;
  4249. }
  4250. }
  4251. /**
  4252. * Handles the branching of alternations. Note this is also used for
  4253. * the ? quantifier to branch between the case where it matches once
  4254. * and where it does not occur.
  4255. */
  4256. static final class Branch extends Node {
  4257. Node[] atoms = new Node[2];
  4258. int size = 2;
  4259. Node conn;
  4260. Branch(Node first, Node second, Node branchConn) {
  4261. conn = branchConn;
  4262. atoms[0] = first;
  4263. atoms[1] = second;
  4264. }
  4265. void add(Node node) {
  4266. if (size >= atoms.length) {
  4267. Node[] tmp = new Node[atoms.length*2];
  4268. System.arraycopy(atoms, 0, tmp, 0, atoms.length);
  4269. atoms = tmp;
  4270. }
  4271. atoms[size++] = node;
  4272. }
  4273. boolean match(Matcher matcher, int i, CharSequence seq) {
  4274. for (int n = 0; n < size; n++) {
  4275. if (atoms[n] == null) {
  4276. if (conn.next.match(matcher, i, seq))
  4277. return true;
  4278. } else if (atoms[n].match(matcher, i, seq)) {
  4279. return true;
  4280. }
  4281. }
  4282. return false;
  4283. }
  4284. boolean study(TreeInfo info) {
  4285. int minL = info.minLength;
  4286. int maxL = info.maxLength;
  4287. boolean maxV = info.maxValid;
  4288. int minL2 = Integer.MAX_VALUE; //arbitrary large enough num
  4289. int maxL2 = -1;
  4290. for (int n = 0; n < size; n++) {
  4291. info.reset();
  4292. if (atoms[n] != null)
  4293. atoms[n].study(info);
  4294. minL2 = Math.min(minL2, info.minLength);
  4295. maxL2 = Math.max(maxL2, info.maxLength);
  4296. maxV = (maxV & info.maxValid);
  4297. }
  4298. minL += minL2;
  4299. maxL += maxL2;
  4300. info.reset();
  4301. conn.next.study(info);
  4302. info.minLength += minL;
  4303. info.maxLength += maxL;
  4304. info.maxValid &= maxV;
  4305. info.deterministic = false;
  4306. return false;
  4307. }
  4308. }
  4309. /**
  4310. * The GroupHead saves the location where the group begins in the locals
  4311. * and restores them when the match is done.
  4312. *
  4313. * The matchRef is used when a reference to this group is accessed later
  4314. * in the expression. The locals will have a negative value in them to
  4315. * indicate that we do not want to unset the group if the reference
  4316. * doesn't match.
  4317. */
  4318. static final class GroupHead extends Node {
  4319. int localIndex;
  4320. GroupHead(int localCount) {
  4321. localIndex = localCount;
  4322. }
  4323. boolean match(Matcher matcher, int i, CharSequence seq) {
  4324. int save = matcher.locals[localIndex];
  4325. matcher.locals[localIndex] = i;
  4326. boolean ret = next.match(matcher, i, seq);
  4327. matcher.locals[localIndex] = save;
  4328. return ret;
  4329. }
  4330. boolean matchRef(Matcher matcher, int i, CharSequence seq) {
  4331. int save = matcher.locals[localIndex];
  4332. matcher.locals[localIndex] = ~i; // HACK
  4333. boolean ret = next.match(matcher, i, seq);
  4334. matcher.locals[localIndex] = save;
  4335. return ret;
  4336. }
  4337. }
  4338. /**
  4339. * Recursive reference to a group in the regular expression. It calls
  4340. * matchRef because if the reference fails to match we would not unset
  4341. * the group.
  4342. */
  4343. static final class GroupRef extends Node {
  4344. GroupHead head;
  4345. GroupRef(GroupHead head) {
  4346. this.head = head;
  4347. }
  4348. boolean match(Matcher matcher, int i, CharSequence seq) {
  4349. return head.matchRef(matcher, i, seq)
  4350. && next.match(matcher, matcher.last, seq);
  4351. }
  4352. boolean study(TreeInfo info) {
  4353. info.maxValid = false;
  4354. info.deterministic = false;
  4355. return next.study(info);
  4356. }
  4357. }
  4358. /**
  4359. * The GroupTail handles the setting of group beginning and ending
  4360. * locations when groups are successfully matched. It must also be able to
  4361. * unset groups that have to be backed off of.
  4362. *
  4363. * The GroupTail node is also used when a previous group is referenced,
  4364. * and in that case no group information needs to be set.
  4365. */
  4366. static final class GroupTail extends Node {
  4367. int localIndex;
  4368. int groupIndex;
  4369. GroupTail(int localCount, int groupCount) {
  4370. localIndex = localCount;
  4371. groupIndex = groupCount + groupCount;
  4372. }
  4373. boolean match(Matcher matcher, int i, CharSequence seq) {
  4374. int tmp = matcher.locals[localIndex];
  4375. if (tmp >= 0) { // This is the normal group case.
  4376. // Save the group so we can unset it if it
  4377. // backs off of a match.
  4378. int groupStart = matcher.groups[groupIndex];
  4379. int groupEnd = matcher.groups[groupIndex+1];
  4380. matcher.groups[groupIndex] = tmp;
  4381. matcher.groups[groupIndex+1] = i;
  4382. if (next.match(matcher, i, seq)) {
  4383. return true;
  4384. }
  4385. matcher.groups[groupIndex] = groupStart;
  4386. matcher.groups[groupIndex+1] = groupEnd;
  4387. return false;
  4388. } else {
  4389. // This is a group reference case. We don't need to save any
  4390. // group info because it isn't really a group.
  4391. matcher.last = i;
  4392. return true;
  4393. }
  4394. }
  4395. }
  4396. /**
  4397. * This sets up a loop to handle a recursive quantifier structure.
  4398. */
  4399. static final class Prolog extends Node {
  4400. Loop loop;
  4401. Prolog(Loop loop) {
  4402. this.loop = loop;
  4403. }
  4404. boolean match(Matcher matcher, int i, CharSequence seq) {
  4405. return loop.matchInit(matcher, i, seq);
  4406. }
  4407. boolean study(TreeInfo info) {
  4408. return loop.study(info);
  4409. }
  4410. }
  4411. /**
  4412. * Handles the repetition count for a greedy Curly. The matchInit
  4413. * is called from the Prolog to save the index of where the group
  4414. * beginning is stored. A zero length group check occurs in the
  4415. * normal match but is skipped in the matchInit.
  4416. */
  4417. static class Loop extends Node {
  4418. Node body;
  4419. int countIndex; // local count index in matcher locals
  4420. int beginIndex; // group beginning index
  4421. int cmin, cmax;
  4422. Loop(int countIndex, int beginIndex) {
  4423. this.countIndex = countIndex;
  4424. this.beginIndex = beginIndex;
  4425. }
  4426. boolean match(Matcher matcher, int i, CharSequence seq) {
  4427. // Avoid infinite loop in zero-length case.
  4428. if (i > matcher.locals[beginIndex]) {
  4429. int count = matcher.locals[countIndex];
  4430. // This block is for before we reach the minimum
  4431. // iterations required for the loop to match
  4432. if (count < cmin) {
  4433. matcher.locals[countIndex] = count + 1;
  4434. boolean b = body.match(matcher, i, seq);
  4435. // If match failed we must backtrack, so
  4436. // the loop count should NOT be incremented
  4437. if (!b)
  4438. matcher.locals[countIndex] = count;
  4439. // Return success or failure since we are under
  4440. // minimum
  4441. return b;
  4442. }
  4443. // This block is for after we have the minimum
  4444. // iterations required for the loop to match
  4445. if (count < cmax) {
  4446. matcher.locals[countIndex] = count + 1;
  4447. boolean b = body.match(matcher, i, seq);
  4448. // If match failed we must backtrack, so
  4449. // the loop count should NOT be incremented
  4450. if (!b)
  4451. matcher.locals[countIndex] = count;
  4452. else
  4453. return true;
  4454. }
  4455. }
  4456. return next.match(matcher, i, seq);
  4457. }
  4458. boolean matchInit(Matcher matcher, int i, CharSequence seq) {
  4459. int save = matcher.locals[countIndex];
  4460. boolean ret = false;
  4461. if (0 < cmin) {
  4462. matcher.locals[countIndex] = 1;
  4463. ret = body.match(matcher, i, seq);
  4464. } else if (0 < cmax) {
  4465. matcher.locals[countIndex] = 1;
  4466. ret = body.match(matcher, i, seq);
  4467. if (ret == false)
  4468. ret = next.match(matcher, i, seq);
  4469. } else {
  4470. ret = next.match(matcher, i, seq);
  4471. }
  4472. matcher.locals[countIndex] = save;
  4473. return ret;
  4474. }
  4475. boolean study(TreeInfo info) {
  4476. info.maxValid = false;
  4477. info.deterministic = false;
  4478. return false;
  4479. }
  4480. }
  4481. /**
  4482. * Handles the repetition count for a reluctant Curly. The matchInit
  4483. * is called from the Prolog to save the index of where the group
  4484. * beginning is stored. A zero length group check occurs in the
  4485. * normal match but is skipped in the matchInit.
  4486. */
  4487. static final class LazyLoop extends Loop {
  4488. LazyLoop(int countIndex, int beginIndex) {
  4489. super(countIndex, beginIndex);
  4490. }
  4491. boolean match(Matcher matcher, int i, CharSequence seq) {
  4492. // Check for zero length group
  4493. if (i > matcher.locals[beginIndex]) {
  4494. int count = matcher.locals[countIndex];
  4495. if (count < cmin) {
  4496. matcher.locals[countIndex] = count + 1;
  4497. boolean result = body.match(matcher, i, seq);
  4498. // If match failed we must backtrack, so
  4499. // the loop count should NOT be incremented
  4500. if (!result)
  4501. matcher.locals[countIndex] = count;
  4502. return result;
  4503. }
  4504. if (next.match(matcher, i, seq))
  4505. return true;
  4506. if (count < cmax) {
  4507. matcher.locals[countIndex] = count + 1;
  4508. boolean result = body.match(matcher, i, seq);
  4509. // If match failed we must backtrack, so
  4510. // the loop count should NOT be incremented
  4511. if (!result)
  4512. matcher.locals[countIndex] = count;
  4513. return result;
  4514. }
  4515. return false;
  4516. }
  4517. return next.match(matcher, i, seq);
  4518. }
  4519. boolean matchInit(Matcher matcher, int i, CharSequence seq) {
  4520. int save = matcher.locals[countIndex];
  4521. boolean ret = false;
  4522. if (0 < cmin) {
  4523. matcher.locals[countIndex] = 1;
  4524. ret = body.match(matcher, i, seq);
  4525. } else if (next.match(matcher, i, seq)) {
  4526. ret = true;
  4527. } else if (0 < cmax) {
  4528. matcher.locals[countIndex] = 1;
  4529. ret = body.match(matcher, i, seq);
  4530. }
  4531. matcher.locals[countIndex] = save;
  4532. return ret;
  4533. }
  4534. boolean study(TreeInfo info) {
  4535. info.maxValid = false;
  4536. info.deterministic = false;
  4537. return false;
  4538. }
  4539. }
  4540. /**
  4541. * Refers to a group in the regular expression. Attempts to match
  4542. * whatever the group referred to last matched.
  4543. */
  4544. static class BackRef extends Node {
  4545. int groupIndex;
  4546. BackRef(int groupCount) {
  4547. super();
  4548. groupIndex = groupCount + groupCount;
  4549. }
  4550. boolean match(Matcher matcher, int i, CharSequence seq) {
  4551. int j = matcher.groups[groupIndex];
  4552. int k = matcher.groups[groupIndex+1];
  4553. int groupSize = k - j;
  4554. // If the referenced group didn't match, neither can this
  4555. if (j < 0)
  4556. return false;
  4557. // If there isn't enough input left no match
  4558. if (i + groupSize > matcher.to) {
  4559. matcher.hitEnd = true;
  4560. return false;
  4561. }
  4562. // Check each new char to make sure it matches what the group
  4563. // referenced matched last time around
  4564. for (int index=0; index<groupSize; index++)
  4565. if (seq.charAt(i+index) != seq.charAt(j+index))
  4566. return false;
  4567. return next.match(matcher, i+groupSize, seq);
  4568. }
  4569. boolean study(TreeInfo info) {
  4570. info.maxValid = false;
  4571. return next.study(info);
  4572. }
  4573. }
  4574. static class CIBackRef extends Node {
  4575. int groupIndex;
  4576. boolean doUnicodeCase;
  4577. CIBackRef(int groupCount, boolean doUnicodeCase) {
  4578. super();
  4579. groupIndex = groupCount + groupCount;
  4580. this.doUnicodeCase = doUnicodeCase;
  4581. }
  4582. boolean match(Matcher matcher, int i, CharSequence seq) {
  4583. int j = matcher.groups[groupIndex];
  4584. int k = matcher.groups[groupIndex+1];
  4585. int groupSize = k - j;
  4586. // If the referenced group didn't match, neither can this
  4587. if (j < 0)
  4588. return false;
  4589. // If there isn't enough input left no match
  4590. if (i + groupSize > matcher.to) {
  4591. matcher.hitEnd = true;
  4592. return false;
  4593. }
  4594. // Check each new char to make sure it matches what the group
  4595. // referenced matched last time around
  4596. int x = i;
  4597. for (int index=0; index<groupSize; index++) {
  4598. int c1 = Character.codePointAt(seq, x);
  4599. int c2 = Character.codePointAt(seq, j);
  4600. if (c1 != c2) {
  4601. if (doUnicodeCase) {
  4602. int cc1 = Character.toUpperCase(c1);
  4603. int cc2 = Character.toUpperCase(c2);
  4604. if (cc1 != cc2 &&
  4605. Character.toLowerCase(cc1) !=
  4606. Character.toLowerCase(cc2))
  4607. return false;
  4608. } else {
  4609. if (ASCII.toLower(c1) != ASCII.toLower(c2))
  4610. return false;
  4611. }
  4612. }
  4613. x += Character.charCount(c1);
  4614. j += Character.charCount(c2);
  4615. }
  4616. return next.match(matcher, i+groupSize, seq);
  4617. }
  4618. boolean study(TreeInfo info) {
  4619. info.maxValid = false;
  4620. return next.study(info);
  4621. }
  4622. }
  4623. /**
  4624. * Searches until the next instance of its atom. This is useful for
  4625. * finding the atom efficiently without passing an instance of it
  4626. * (greedy problem) and without a lot of wasted search time (reluctant
  4627. * problem).
  4628. */
  4629. static final class First extends Node {
  4630. Node atom;
  4631. First(Node node) {
  4632. this.atom = BnM.optimize(node);
  4633. }
  4634. boolean match(Matcher matcher, int i, CharSequence seq) {
  4635. if (atom instanceof BnM) {
  4636. return atom.match(matcher, i, seq)
  4637. && next.match(matcher, matcher.last, seq);
  4638. }
  4639. for (;;) {
  4640. if (i > matcher.to) {
  4641. matcher.hitEnd = true;
  4642. return false;
  4643. }
  4644. if (atom.match(matcher, i, seq)) {
  4645. return next.match(matcher, matcher.last, seq);
  4646. }
  4647. i += countChars(seq, i, 1);
  4648. matcher.first++;
  4649. }
  4650. }
  4651. boolean study(TreeInfo info) {
  4652. atom.study(info);
  4653. info.maxValid = false;
  4654. info.deterministic = false;
  4655. return next.study(info);
  4656. }
  4657. }
  4658. static final class Conditional extends Node {
  4659. Node cond, yes, not;
  4660. Conditional(Node cond, Node yes, Node not) {
  4661. this.cond = cond;
  4662. this.yes = yes;
  4663. this.not = not;
  4664. }
  4665. boolean match(Matcher matcher, int i, CharSequence seq) {
  4666. if (cond.match(matcher, i, seq)) {
  4667. return yes.match(matcher, i, seq);
  4668. } else {
  4669. return not.match(matcher, i, seq);
  4670. }
  4671. }
  4672. boolean study(TreeInfo info) {
  4673. int minL = info.minLength;
  4674. int maxL = info.maxLength;
  4675. boolean maxV = info.maxValid;
  4676. info.reset();
  4677. yes.study(info);
  4678. int minL2 = info.minLength;
  4679. int maxL2 = info.maxLength;
  4680. boolean maxV2 = info.maxValid;
  4681. info.reset();
  4682. not.study(info);
  4683. info.minLength = minL + Math.min(minL2, info.minLength);
  4684. info.maxLength = maxL + Math.max(maxL2, info.maxLength);
  4685. info.maxValid = (maxV & maxV2 & info.maxValid);
  4686. info.deterministic = false;
  4687. return next.study(info);
  4688. }
  4689. }
  4690. /**
  4691. * Zero width positive lookahead.
  4692. */
  4693. static final class Pos extends Node {
  4694. Node cond;
  4695. Pos(Node cond) {
  4696. this.cond = cond;
  4697. }
  4698. boolean match(Matcher matcher, int i, CharSequence seq) {
  4699. int savedTo = matcher.to;
  4700. boolean conditionMatched = false;
  4701. // Relax transparent region boundaries for lookahead
  4702. if (matcher.transparentBounds)
  4703. matcher.to = matcher.getTextLength();
  4704. try {
  4705. conditionMatched = cond.match(matcher, i, seq);
  4706. } finally {
  4707. // Reinstate region boundaries
  4708. matcher.to = savedTo;
  4709. }
  4710. return conditionMatched && next.match(matcher, i, seq);
  4711. }
  4712. }
  4713. /**
  4714. * Zero width negative lookahead.
  4715. */
  4716. static final class Neg extends Node {
  4717. Node cond;
  4718. Neg(Node cond) {
  4719. this.cond = cond;
  4720. }
  4721. boolean match(Matcher matcher, int i, CharSequence seq) {
  4722. int savedTo = matcher.to;
  4723. boolean conditionMatched = false;
  4724. // Relax transparent region boundaries for lookahead
  4725. if (matcher.transparentBounds)
  4726. matcher.to = matcher.getTextLength();
  4727. try {
  4728. if (i < matcher.to) {
  4729. conditionMatched = !cond.match(matcher, i, seq);
  4730. } else {
  4731. // If a negative lookahead succeeds then more input
  4732. // could cause it to fail!
  4733. matcher.requireEnd = true;
  4734. conditionMatched = !cond.match(matcher, i, seq);
  4735. }
  4736. } finally {
  4737. // Reinstate region boundaries
  4738. matcher.to = savedTo;
  4739. }
  4740. return conditionMatched && next.match(matcher, i, seq);
  4741. }
  4742. }
  4743. /**
  4744. * For use with lookbehinds; matches the position where the lookbehind
  4745. * was encountered.
  4746. */
  4747. static Node lookbehindEnd = new Node() {
  4748. boolean match(Matcher matcher, int i, CharSequence seq) {
  4749. return i == matcher.lookbehindTo;
  4750. }
  4751. };
  4752. /**
  4753. * Zero width positive lookbehind.
  4754. */
  4755. static class Behind extends Node {
  4756. Node cond;
  4757. int rmax, rmin;
  4758. Behind(Node cond, int rmax, int rmin) {
  4759. this.cond = cond;
  4760. this.rmax = rmax;
  4761. this.rmin = rmin;
  4762. }
  4763. boolean match(Matcher matcher, int i, CharSequence seq) {
  4764. int savedFrom = matcher.from;
  4765. boolean conditionMatched = false;
  4766. int startIndex = (!matcher.transparentBounds) ?
  4767. matcher.from : 0;
  4768. int from = Math.max(i - rmax, startIndex);
  4769. // Set end boundary
  4770. int savedLBT = matcher.lookbehindTo;
  4771. matcher.lookbehindTo = i;
  4772. // Relax transparent region boundaries for lookbehind
  4773. if (matcher.transparentBounds)
  4774. matcher.from = 0;
  4775. for (int j = i - rmin; !conditionMatched && j >= from; j--) {
  4776. conditionMatched = cond.match(matcher, j, seq);
  4777. }
  4778. matcher.from = savedFrom;
  4779. matcher.lookbehindTo = savedLBT;
  4780. return conditionMatched && next.match(matcher, i, seq);
  4781. }
  4782. }
  4783. /**
  4784. * Zero width positive lookbehind, including supplementary
  4785. * characters or unpaired surrogates.
  4786. */
  4787. static final class BehindS extends Behind {
  4788. BehindS(Node cond, int rmax, int rmin) {
  4789. super(cond, rmax, rmin);
  4790. }
  4791. boolean match(Matcher matcher, int i, CharSequence seq) {
  4792. int rmaxChars = countChars(seq, i, -rmax);
  4793. int rminChars = countChars(seq, i, -rmin);
  4794. int savedFrom = matcher.from;
  4795. int startIndex = (!matcher.transparentBounds) ?
  4796. matcher.from : 0;
  4797. boolean conditionMatched = false;
  4798. int from = Math.max(i - rmaxChars, startIndex);
  4799. // Set end boundary
  4800. int savedLBT = matcher.lookbehindTo;
  4801. matcher.lookbehindTo = i;
  4802. // Relax transparent region boundaries for lookbehind
  4803. if (matcher.transparentBounds)
  4804. matcher.from = 0;
  4805. for (int j = i - rminChars;
  4806. !conditionMatched && j >= from;
  4807. j -= j>from ? countChars(seq, j, -1) : 1) {
  4808. conditionMatched = cond.match(matcher, j, seq);
  4809. }
  4810. matcher.from = savedFrom;
  4811. matcher.lookbehindTo = savedLBT;
  4812. return conditionMatched && next.match(matcher, i, seq);
  4813. }
  4814. }
  4815. /**
  4816. * Zero width negative lookbehind.
  4817. */
  4818. static class NotBehind extends Node {
  4819. Node cond;
  4820. int rmax, rmin;
  4821. NotBehind(Node cond, int rmax, int rmin) {
  4822. this.cond = cond;
  4823. this.rmax = rmax;
  4824. this.rmin = rmin;
  4825. }
  4826. boolean match(Matcher matcher, int i, CharSequence seq) {
  4827. int savedLBT = matcher.lookbehindTo;
  4828. int savedFrom = matcher.from;
  4829. boolean conditionMatched = false;
  4830. int startIndex = (!matcher.transparentBounds) ?
  4831. matcher.from : 0;
  4832. int from = Math.max(i - rmax, startIndex);
  4833. matcher.lookbehindTo = i;
  4834. // Relax transparent region boundaries for lookbehind
  4835. if (matcher.transparentBounds)
  4836. matcher.from = 0;
  4837. for (int j = i - rmin; !conditionMatched && j >= from; j--) {
  4838. conditionMatched = cond.match(matcher, j, seq);
  4839. }
  4840. // Reinstate region boundaries
  4841. matcher.from = savedFrom;
  4842. matcher.lookbehindTo = savedLBT;
  4843. return !conditionMatched && next.match(matcher, i, seq);
  4844. }
  4845. }
  4846. /**
  4847. * Zero width negative lookbehind, including supplementary
  4848. * characters or unpaired surrogates.
  4849. */
  4850. static final class NotBehindS extends NotBehind {
  4851. NotBehindS(Node cond, int rmax, int rmin) {
  4852. super(cond, rmax, rmin);
  4853. }
  4854. boolean match(Matcher matcher, int i, CharSequence seq) {
  4855. int rmaxChars = countChars(seq, i, -rmax);
  4856. int rminChars = countChars(seq, i, -rmin);
  4857. int savedFrom = matcher.from;
  4858. int savedLBT = matcher.lookbehindTo;
  4859. boolean conditionMatched = false;
  4860. int startIndex = (!matcher.transparentBounds) ?
  4861. matcher.from : 0;
  4862. int from = Math.max(i - rmaxChars, startIndex);
  4863. matcher.lookbehindTo = i;
  4864. // Relax transparent region boundaries for lookbehind
  4865. if (matcher.transparentBounds)
  4866. matcher.from = 0;
  4867. for (int j = i - rminChars;
  4868. !conditionMatched && j >= from;
  4869. j -= j>from ? countChars(seq, j, -1) : 1) {
  4870. conditionMatched = cond.match(matcher, j, seq);
  4871. }
  4872. //Reinstate region boundaries
  4873. matcher.from = savedFrom;
  4874. matcher.lookbehindTo = savedLBT;
  4875. return !conditionMatched && next.match(matcher, i, seq);
  4876. }
  4877. }
  4878. /**
  4879. * Returns the set union of two CharProperty nodes.
  4880. */
  4881. private static CharProperty union(final CharProperty lhs,
  4882. final CharProperty rhs) {
  4883. return new CharProperty() {
  4884. boolean isSatisfiedBy(int ch) {
  4885. return lhs.isSatisfiedBy(ch) || rhs.isSatisfiedBy(ch);}};
  4886. }
  4887. /**
  4888. * Returns the set intersection of two CharProperty nodes.
  4889. */
  4890. private static CharProperty intersection(final CharProperty lhs,
  4891. final CharProperty rhs) {
  4892. return new CharProperty() {
  4893. boolean isSatisfiedBy(int ch) {
  4894. return lhs.isSatisfiedBy(ch) && rhs.isSatisfiedBy(ch);}};
  4895. }
  4896. /**
  4897. * Returns the set difference of two CharProperty nodes.
  4898. */
  4899. private static CharProperty setDifference(final CharProperty lhs,
  4900. final CharProperty rhs) {
  4901. return new CharProperty() {
  4902. boolean isSatisfiedBy(int ch) {
  4903. return ! rhs.isSatisfiedBy(ch) && lhs.isSatisfiedBy(ch);}};
  4904. }
  4905. /**
  4906. * Handles word boundaries. Includes a field to allow this one class to
  4907. * deal with the different types of word boundaries we can match. The word
  4908. * characters include underscores, letters, and digits. Non spacing marks
  4909. * can are also part of a word if they have a base character, otherwise
  4910. * they are ignored for purposes of finding word boundaries.
  4911. */
  4912. static final class Bound extends Node {
  4913. static int LEFT = 0x1;
  4914. static int RIGHT= 0x2;
  4915. static int BOTH = 0x3;
  4916. static int NONE = 0x4;
  4917. int type;
  4918. boolean useUWORD;
  4919. Bound(int n, boolean useUWORD) {
  4920. type = n;
  4921. this.useUWORD = useUWORD;
  4922. }
  4923. boolean isWord(int ch) {
  4924. return useUWORD ? UnicodeProp.WORD.is(ch)
  4925. : (ch == '_' || Character.isLetterOrDigit(ch));
  4926. }
  4927. int check(Matcher matcher, int i, CharSequence seq) {
  4928. int ch;
  4929. boolean left = false;
  4930. int startIndex = matcher.from;
  4931. int endIndex = matcher.to;
  4932. if (matcher.transparentBounds) {
  4933. startIndex = 0;
  4934. endIndex = matcher.getTextLength();
  4935. }
  4936. if (i > startIndex) {
  4937. ch = Character.codePointBefore(seq, i);
  4938. left = (isWord(ch) ||
  4939. ((Character.getType(ch) == Character.NON_SPACING_MARK)
  4940. && hasBaseCharacter(matcher, i-1, seq)));
  4941. }
  4942. boolean right = false;
  4943. if (i < endIndex) {
  4944. ch = Character.codePointAt(seq, i);
  4945. right = (isWord(ch) ||
  4946. ((Character.getType(ch) == Character.NON_SPACING_MARK)
  4947. && hasBaseCharacter(matcher, i, seq)));
  4948. } else {
  4949. // Tried to access char past the end
  4950. matcher.hitEnd = true;
  4951. // The addition of another char could wreck a boundary
  4952. matcher.requireEnd = true;
  4953. }
  4954. return ((left ^ right) ? (right ? LEFT : RIGHT) : NONE);
  4955. }
  4956. boolean match(Matcher matcher, int i, CharSequence seq) {
  4957. return (check(matcher, i, seq) & type) > 0
  4958. && next.match(matcher, i, seq);
  4959. }
  4960. }
  4961. /**
  4962. * Non spacing marks only count as word characters in bounds calculations
  4963. * if they have a base character.
  4964. */
  4965. private static boolean hasBaseCharacter(Matcher matcher, int i,
  4966. CharSequence seq)
  4967. {
  4968. int start = (!matcher.transparentBounds) ?
  4969. matcher.from : 0;
  4970. for (int x=i; x >= start; x--) {
  4971. int ch = Character.codePointAt(seq, x);
  4972. if (Character.isLetterOrDigit(ch))
  4973. return true;
  4974. if (Character.getType(ch) == Character.NON_SPACING_MARK)
  4975. continue;
  4976. return false;
  4977. }
  4978. return false;
  4979. }
  4980. /**
  4981. * Attempts to match a slice in the input using the Boyer-Moore string
  4982. * matching algorithm. The algorithm is based on the idea that the
  4983. * pattern can be shifted farther ahead in the search text if it is
  4984. * matched right to left.
  4985. * <p>
  4986. * The pattern is compared to the input one character at a time, from
  4987. * the rightmost character in the pattern to the left. If the characters
  4988. * all match the pattern has been found. If a character does not match,
  4989. * the pattern is shifted right a distance that is the maximum of two
  4990. * functions, the bad character shift and the good suffix shift. This
  4991. * shift moves the attempted match position through the input more
  4992. * quickly than a naive one position at a time check.
  4993. * <p>
  4994. * The bad character shift is based on the character from the text that
  4995. * did not match. If the character does not appear in the pattern, the
  4996. * pattern can be shifted completely beyond the bad character. If the
  4997. * character does occur in the pattern, the pattern can be shifted to
  4998. * line the pattern up with the next occurrence of that character.
  4999. * <p>
  5000. * The good suffix shift is based on the idea that some subset on the right
  5001. * side of the pattern has matched. When a bad character is found, the
  5002. * pattern can be shifted right by the pattern length if the subset does
  5003. * not occur again in pattern, or by the amount of distance to the
  5004. * next occurrence of the subset in the pattern.
  5005. *
  5006. * Boyer-Moore search methods adapted from code by Amy Yu.
  5007. */
  5008. static class BnM extends Node {
  5009. int[] buffer;
  5010. int[] lastOcc;
  5011. int[] optoSft;
  5012. /**
  5013. * Pre calculates arrays needed to generate the bad character
  5014. * shift and the good suffix shift. Only the last seven bits
  5015. * are used to see if chars match; This keeps the tables small
  5016. * and covers the heavily used ASCII range, but occasionally
  5017. * results in an aliased match for the bad character shift.
  5018. */
  5019. static Node optimize(Node node) {
  5020. if (!(node instanceof Slice)) {
  5021. return node;
  5022. }
  5023. int[] src = ((Slice) node).buffer;
  5024. int patternLength = src.length;
  5025. // The BM algorithm requires a bit of overhead;
  5026. // If the pattern is short don't use it, since
  5027. // a shift larger than the pattern length cannot
  5028. // be used anyway.
  5029. if (patternLength < 4) {
  5030. return node;
  5031. }
  5032. int i, j, k;
  5033. int[] lastOcc = new int[128];
  5034. int[] optoSft = new int[patternLength];
  5035. // Precalculate part of the bad character shift
  5036. // It is a table for where in the pattern each
  5037. // lower 7-bit value occurs
  5038. for (i = 0; i < patternLength; i++) {
  5039. lastOcc[src[i]&0x7F] = i + 1;
  5040. }
  5041. // Precalculate the good suffix shift
  5042. // i is the shift amount being considered
  5043. NEXT: for (i = patternLength; i > 0; i--) {
  5044. // j is the beginning index of suffix being considered
  5045. for (j = patternLength - 1; j >= i; j--) {
  5046. // Testing for good suffix
  5047. if (src[j] == src[j-i]) {
  5048. // src[j..len] is a good suffix
  5049. optoSft[j-1] = i;
  5050. } else {
  5051. // No match. The array has already been
  5052. // filled up with correct values before.
  5053. continue NEXT;
  5054. }
  5055. }
  5056. // This fills up the remaining of optoSft
  5057. // any suffix can not have larger shift amount
  5058. // then its sub-suffix. Why???
  5059. while (j > 0) {
  5060. optoSft[--j] = i;
  5061. }
  5062. }
  5063. // Set the guard value because of unicode compression
  5064. optoSft[patternLength-1] = 1;
  5065. if (node instanceof SliceS)
  5066. return new BnMS(src, lastOcc, optoSft, node.next);
  5067. return new BnM(src, lastOcc, optoSft, node.next);
  5068. }
  5069. BnM(int[] src, int[] lastOcc, int[] optoSft, Node next) {
  5070. this.buffer = src;
  5071. this.lastOcc = lastOcc;
  5072. this.optoSft = optoSft;
  5073. this.next = next;
  5074. }
  5075. boolean match(Matcher matcher, int i, CharSequence seq) {
  5076. int[] src = buffer;
  5077. int patternLength = src.length;
  5078. int last = matcher.to - patternLength;
  5079. // Loop over all possible match positions in text
  5080. NEXT: while (i <= last) {
  5081. // Loop over pattern from right to left
  5082. for (int j = patternLength - 1; j >= 0; j--) {
  5083. int ch = seq.charAt(i+j);
  5084. if (ch != src[j]) {
  5085. // Shift search to the right by the maximum of the
  5086. // bad character shift and the good suffix shift
  5087. i += Math.max(j + 1 - lastOcc[ch&0x7F], optoSft[j]);
  5088. continue NEXT;
  5089. }
  5090. }
  5091. // Entire pattern matched starting at i
  5092. matcher.first = i;
  5093. boolean ret = next.match(matcher, i + patternLength, seq);
  5094. if (ret) {
  5095. matcher.first = i;
  5096. matcher.groups[0] = matcher.first;
  5097. matcher.groups[1] = matcher.last;
  5098. return true;
  5099. }
  5100. i++;
  5101. }
  5102. // BnM is only used as the leading node in the unanchored case,
  5103. // and it replaced its Start() which always searches to the end
  5104. // if it doesn't find what it's looking for, so hitEnd is true.
  5105. matcher.hitEnd = true;
  5106. return false;
  5107. }
  5108. boolean study(TreeInfo info) {
  5109. info.minLength += buffer.length;
  5110. info.maxValid = false;
  5111. return next.study(info);
  5112. }
  5113. }
  5114. /**
  5115. * Supplementary support version of BnM(). Unpaired surrogates are
  5116. * also handled by this class.
  5117. */
  5118. static final class BnMS extends BnM {
  5119. int lengthInChars;
  5120. BnMS(int[] src, int[] lastOcc, int[] optoSft, Node next) {
  5121. super(src, lastOcc, optoSft, next);
  5122. for (int x = 0; x < buffer.length; x++) {
  5123. lengthInChars += Character.charCount(buffer[x]);
  5124. }
  5125. }
  5126. boolean match(Matcher matcher, int i, CharSequence seq) {
  5127. int[] src = buffer;
  5128. int patternLength = src.length;
  5129. int last = matcher.to - lengthInChars;
  5130. // Loop over all possible match positions in text
  5131. NEXT: while (i <= last) {
  5132. // Loop over pattern from right to left
  5133. int ch;
  5134. for (int j = countChars(seq, i, patternLength), x = patternLength - 1;
  5135. j > 0; j -= Character.charCount(ch), x--) {
  5136. ch = Character.codePointBefore(seq, i+j);
  5137. if (ch != src[x]) {
  5138. // Shift search to the right by the maximum of the
  5139. // bad character shift and the good suffix shift
  5140. int n = Math.max(x + 1 - lastOcc[ch&0x7F], optoSft[x]);
  5141. i += countChars(seq, i, n);
  5142. continue NEXT;
  5143. }
  5144. }
  5145. // Entire pattern matched starting at i
  5146. matcher.first = i;
  5147. boolean ret = next.match(matcher, i + lengthInChars, seq);
  5148. if (ret) {
  5149. matcher.first = i;
  5150. matcher.groups[0] = matcher.first;
  5151. matcher.groups[1] = matcher.last;
  5152. return true;
  5153. }
  5154. i += countChars(seq, i, 1);
  5155. }
  5156. matcher.hitEnd = true;
  5157. return false;
  5158. }
  5159. }
  5160. ///////////////////////////////////////////////////////////////////////////////
  5161. ///////////////////////////////////////////////////////////////////////////////
  5162. /**
  5163. * This must be the very first initializer.
  5164. */
  5165. static Node accept = new Node();
  5166. static Node lastAccept = new LastNode();
  5167. private static class CharPropertyNames {
  5168. static CharProperty charPropertyFor(String name) {
  5169. CharPropertyFactory m = map.get(name);
  5170. return m == null ? null : m.make();
  5171. }
  5172. private static abstract class CharPropertyFactory {
  5173. abstract CharProperty make();
  5174. }
  5175. private static void defCategory(String name,
  5176. final int typeMask) {
  5177. map.put(name, new CharPropertyFactory() {
  5178. CharProperty make() { return new Category(typeMask);}});
  5179. }
  5180. private static void defRange(String name,
  5181. final int lower, final int upper) {
  5182. map.put(name, new CharPropertyFactory() {
  5183. CharProperty make() { return rangeFor(lower, upper);}});
  5184. }
  5185. private static void defCtype(String name,
  5186. final int ctype) {
  5187. map.put(name, new CharPropertyFactory() {
  5188. CharProperty make() { return new Ctype(ctype);}});
  5189. }
  5190. private static abstract class CloneableProperty
  5191. extends CharProperty implements Cloneable
  5192. {
  5193. public CloneableProperty clone() {
  5194. try {
  5195. return (CloneableProperty) super.clone();
  5196. } catch (CloneNotSupportedException e) {
  5197. throw new AssertionError(e);
  5198. }
  5199. }
  5200. }
  5201. private static void defClone(String name,
  5202. final CloneableProperty p) {
  5203. map.put(name, new CharPropertyFactory() {
  5204. CharProperty make() { return p.clone();}});
  5205. }
  5206. private static final HashMap<String, CharPropertyFactory> map
  5207. = new HashMap<>();
  5208. static {
  5209. // Unicode character property aliases, defined in
  5210. // http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt
  5211. defCategory("Cn", 1<<Character.UNASSIGNED);
  5212. defCategory("Lu", 1<<Character.UPPERCASE_LETTER);
  5213. defCategory("Ll", 1<<Character.LOWERCASE_LETTER);
  5214. defCategory("Lt", 1<<Character.TITLECASE_LETTER);
  5215. defCategory("Lm", 1<<Character.MODIFIER_LETTER);
  5216. defCategory("Lo", 1<<Character.OTHER_LETTER);
  5217. defCategory("Mn", 1<<Character.NON_SPACING_MARK);
  5218. defCategory("Me", 1<<Character.ENCLOSING_MARK);
  5219. defCategory("Mc", 1<<Character.COMBINING_SPACING_MARK);
  5220. defCategory("Nd", 1<<Character.DECIMAL_DIGIT_NUMBER);
  5221. defCategory("Nl", 1<<Character.LETTER_NUMBER);
  5222. defCategory("No", 1<<Character.OTHER_NUMBER);
  5223. defCategory("Zs", 1<<Character.SPACE_SEPARATOR);
  5224. defCategory("Zl", 1<<Character.LINE_SEPARATOR);
  5225. defCategory("Zp", 1<<Character.PARAGRAPH_SEPARATOR);
  5226. defCategory("Cc", 1<<Character.CONTROL);
  5227. defCategory("Cf", 1<<Character.FORMAT);
  5228. defCategory("Co", 1<<Character.PRIVATE_USE);
  5229. defCategory("Cs", 1<<Character.SURROGATE);
  5230. defCategory("Pd", 1<<Character.DASH_PUNCTUATION);
  5231. defCategory("Ps", 1<<Character.START_PUNCTUATION);
  5232. defCategory("Pe", 1<<Character.END_PUNCTUATION);
  5233. defCategory("Pc", 1<<Character.CONNECTOR_PUNCTUATION);
  5234. defCategory("Po", 1<<Character.OTHER_PUNCTUATION);
  5235. defCategory("Sm", 1<<Character.MATH_SYMBOL);
  5236. defCategory("Sc", 1<<Character.CURRENCY_SYMBOL);
  5237. defCategory("Sk", 1<<Character.MODIFIER_SYMBOL);
  5238. defCategory("So", 1<<Character.OTHER_SYMBOL);
  5239. defCategory("Pi", 1<<Character.INITIAL_QUOTE_PUNCTUATION);
  5240. defCategory("Pf", 1<<Character.FINAL_QUOTE_PUNCTUATION);
  5241. defCategory("L", ((1<<Character.UPPERCASE_LETTER) |
  5242. (1<<Character.LOWERCASE_LETTER) |
  5243. (1<<Character.TITLECASE_LETTER) |
  5244. (1<<Character.MODIFIER_LETTER) |
  5245. (1<<Character.OTHER_LETTER)));
  5246. defCategory("M", ((1<<Character.NON_SPACING_MARK) |
  5247. (1<<Character.ENCLOSING_MARK) |
  5248. (1<<Character.COMBINING_SPACING_MARK)));
  5249. defCategory("N", ((1<<Character.DECIMAL_DIGIT_NUMBER) |
  5250. (1<<Character.LETTER_NUMBER) |
  5251. (1<<Character.OTHER_NUMBER)));
  5252. defCategory("Z", ((1<<Character.SPACE_SEPARATOR) |
  5253. (1<<Character.LINE_SEPARATOR) |
  5254. (1<<Character.PARAGRAPH_SEPARATOR)));
  5255. defCategory("C", ((1<<Character.CONTROL) |
  5256. (1<<Character.FORMAT) |
  5257. (1<<Character.PRIVATE_USE) |
  5258. (1<<Character.SURROGATE))); // Other
  5259. defCategory("P", ((1<<Character.DASH_PUNCTUATION) |
  5260. (1<<Character.START_PUNCTUATION) |
  5261. (1<<Character.END_PUNCTUATION) |
  5262. (1<<Character.CONNECTOR_PUNCTUATION) |
  5263. (1<<Character.OTHER_PUNCTUATION) |
  5264. (1<<Character.INITIAL_QUOTE_PUNCTUATION) |
  5265. (1<<Character.FINAL_QUOTE_PUNCTUATION)));
  5266. defCategory("S", ((1<<Character.MATH_SYMBOL) |
  5267. (1<<Character.CURRENCY_SYMBOL) |
  5268. (1<<Character.MODIFIER_SYMBOL) |
  5269. (1<<Character.OTHER_SYMBOL)));
  5270. defCategory("LC", ((1<<Character.UPPERCASE_LETTER) |
  5271. (1<<Character.LOWERCASE_LETTER) |
  5272. (1<<Character.TITLECASE_LETTER)));
  5273. defCategory("LD", ((1<<Character.UPPERCASE_LETTER) |
  5274. (1<<Character.LOWERCASE_LETTER) |
  5275. (1<<Character.TITLECASE_LETTER) |
  5276. (1<<Character.MODIFIER_LETTER) |
  5277. (1<<Character.OTHER_LETTER) |
  5278. (1<<Character.DECIMAL_DIGIT_NUMBER)));
  5279. defRange("L1", 0x00, 0xFF); // Latin-1
  5280. map.put("all", new CharPropertyFactory() {
  5281. CharProperty make() { return new All(); }});
  5282. // Posix regular expression character classes, defined in
  5283. // http://www.unix.org/onlinepubs/009695399/basedefs/xbd_chap09.html
  5284. defRange("ASCII", 0x00, 0x7F); // ASCII
  5285. defCtype("Alnum", ASCII.ALNUM); // Alphanumeric characters
  5286. defCtype("Alpha", ASCII.ALPHA); // Alphabetic characters
  5287. defCtype("Blank", ASCII.BLANK); // Space and tab characters
  5288. defCtype("Cntrl", ASCII.CNTRL); // Control characters
  5289. defRange("Digit", '0', '9'); // Numeric characters
  5290. defCtype("Graph", ASCII.GRAPH); // printable and visible
  5291. defRange("Lower", 'a', 'z'); // Lower-case alphabetic
  5292. defRange("Print", 0x20, 0x7E); // Printable characters
  5293. defCtype("Punct", ASCII.PUNCT); // Punctuation characters
  5294. defCtype("Space", ASCII.SPACE); // Space characters
  5295. defRange("Upper", 'A', 'Z'); // Upper-case alphabetic
  5296. defCtype("XDigit",ASCII.XDIGIT); // hexadecimal digits
  5297. // Java character properties, defined by methods in Character.java
  5298. defClone("javaLowerCase", new CloneableProperty() {
  5299. boolean isSatisfiedBy(int ch) {
  5300. return Character.isLowerCase(ch);}});
  5301. defClone("javaUpperCase", new CloneableProperty() {
  5302. boolean isSatisfiedBy(int ch) {
  5303. return Character.isUpperCase(ch);}});
  5304. defClone("javaAlphabetic", new CloneableProperty() {
  5305. boolean isSatisfiedBy(int ch) {
  5306. return Character.isAlphabetic(ch);}});
  5307. defClone("javaIdeographic", new CloneableProperty() {
  5308. boolean isSatisfiedBy(int ch) {
  5309. return Character.isIdeographic(ch);}});
  5310. defClone("javaTitleCase", new CloneableProperty() {
  5311. boolean isSatisfiedBy(int ch) {
  5312. return Character.isTitleCase(ch);}});
  5313. defClone("javaDigit", new CloneableProperty() {
  5314. boolean isSatisfiedBy(int ch) {
  5315. return Character.isDigit(ch);}});
  5316. defClone("javaDefined", new CloneableProperty() {
  5317. boolean isSatisfiedBy(int ch) {
  5318. return Character.isDefined(ch);}});
  5319. defClone("javaLetter", new CloneableProperty() {
  5320. boolean isSatisfiedBy(int ch) {
  5321. return Character.isLetter(ch);}});
  5322. defClone("javaLetterOrDigit", new CloneableProperty() {
  5323. boolean isSatisfiedBy(int ch) {
  5324. return Character.isLetterOrDigit(ch);}});
  5325. defClone("javaJavaIdentifierStart", new CloneableProperty() {
  5326. boolean isSatisfiedBy(int ch) {
  5327. return Character.isJavaIdentifierStart(ch);}});
  5328. defClone("javaJavaIdentifierPart", new CloneableProperty() {
  5329. boolean isSatisfiedBy(int ch) {
  5330. return Character.isJavaIdentifierPart(ch);}});
  5331. defClone("javaUnicodeIdentifierStart", new CloneableProperty() {
  5332. boolean isSatisfiedBy(int ch) {
  5333. return Character.isUnicodeIdentifierStart(ch);}});
  5334. defClone("javaUnicodeIdentifierPart", new CloneableProperty() {
  5335. boolean isSatisfiedBy(int ch) {
  5336. return Character.isUnicodeIdentifierPart(ch);}});
  5337. defClone("javaIdentifierIgnorable", new CloneableProperty() {
  5338. boolean isSatisfiedBy(int ch) {
  5339. return Character.isIdentifierIgnorable(ch);}});
  5340. defClone("javaSpaceChar", new CloneableProperty() {
  5341. boolean isSatisfiedBy(int ch) {
  5342. return Character.isSpaceChar(ch);}});
  5343. defClone("javaWhitespace", new CloneableProperty() {
  5344. boolean isSatisfiedBy(int ch) {
  5345. return Character.isWhitespace(ch);}});
  5346. defClone("javaISOControl", new CloneableProperty() {
  5347. boolean isSatisfiedBy(int ch) {
  5348. return Character.isISOControl(ch);}});
  5349. defClone("javaMirrored", new CloneableProperty() {
  5350. boolean isSatisfiedBy(int ch) {
  5351. return Character.isMirrored(ch);}});
  5352. }
  5353. }
  5354. }