1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/rt/emul/compact/src/main/java/java/util/regex/ASCII.java Mon Oct 07 16:13:27 2013 +0200
1.3 @@ -0,0 +1,274 @@
1.4 +/*
1.5 + * Copyright (c) 1999, 2000, Oracle and/or its affiliates. All rights reserved.
1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1.7 + *
1.8 + * This code is free software; you can redistribute it and/or modify it
1.9 + * under the terms of the GNU General Public License version 2 only, as
1.10 + * published by the Free Software Foundation. Oracle designates this
1.11 + * particular file as subject to the "Classpath" exception as provided
1.12 + * by Oracle in the LICENSE file that accompanied this code.
1.13 + *
1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1.17 + * version 2 for more details (a copy is included in the LICENSE file that
1.18 + * accompanied this code).
1.19 + *
1.20 + * You should have received a copy of the GNU General Public License version
1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1.23 + *
1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
1.25 + * or visit www.oracle.com if you need additional information or have any
1.26 + * questions.
1.27 + */
1.28 +
1.29 +package java.util.regex;
1.30 +
1.31 +
1.32 +/**
1.33 + * Utility class that implements the standard C ctype functionality.
1.34 + *
1.35 + * @author Hong Zhang
1.36 + */
1.37 +
1.38 +final class ASCII {
1.39 +
1.40 + static final int UPPER = 0x00000100;
1.41 +
1.42 + static final int LOWER = 0x00000200;
1.43 +
1.44 + static final int DIGIT = 0x00000400;
1.45 +
1.46 + static final int SPACE = 0x00000800;
1.47 +
1.48 + static final int PUNCT = 0x00001000;
1.49 +
1.50 + static final int CNTRL = 0x00002000;
1.51 +
1.52 + static final int BLANK = 0x00004000;
1.53 +
1.54 + static final int HEX = 0x00008000;
1.55 +
1.56 + static final int UNDER = 0x00010000;
1.57 +
1.58 + static final int ASCII = 0x0000FF00;
1.59 +
1.60 + static final int ALPHA = (UPPER|LOWER);
1.61 +
1.62 + static final int ALNUM = (UPPER|LOWER|DIGIT);
1.63 +
1.64 + static final int GRAPH = (PUNCT|UPPER|LOWER|DIGIT);
1.65 +
1.66 + static final int WORD = (UPPER|LOWER|UNDER|DIGIT);
1.67 +
1.68 + static final int XDIGIT = (HEX);
1.69 +
1.70 + private static final int[] ctype = new int[] {
1.71 + CNTRL, /* 00 (NUL) */
1.72 + CNTRL, /* 01 (SOH) */
1.73 + CNTRL, /* 02 (STX) */
1.74 + CNTRL, /* 03 (ETX) */
1.75 + CNTRL, /* 04 (EOT) */
1.76 + CNTRL, /* 05 (ENQ) */
1.77 + CNTRL, /* 06 (ACK) */
1.78 + CNTRL, /* 07 (BEL) */
1.79 + CNTRL, /* 08 (BS) */
1.80 + SPACE+CNTRL+BLANK, /* 09 (HT) */
1.81 + SPACE+CNTRL, /* 0A (LF) */
1.82 + SPACE+CNTRL, /* 0B (VT) */
1.83 + SPACE+CNTRL, /* 0C (FF) */
1.84 + SPACE+CNTRL, /* 0D (CR) */
1.85 + CNTRL, /* 0E (SI) */
1.86 + CNTRL, /* 0F (SO) */
1.87 + CNTRL, /* 10 (DLE) */
1.88 + CNTRL, /* 11 (DC1) */
1.89 + CNTRL, /* 12 (DC2) */
1.90 + CNTRL, /* 13 (DC3) */
1.91 + CNTRL, /* 14 (DC4) */
1.92 + CNTRL, /* 15 (NAK) */
1.93 + CNTRL, /* 16 (SYN) */
1.94 + CNTRL, /* 17 (ETB) */
1.95 + CNTRL, /* 18 (CAN) */
1.96 + CNTRL, /* 19 (EM) */
1.97 + CNTRL, /* 1A (SUB) */
1.98 + CNTRL, /* 1B (ESC) */
1.99 + CNTRL, /* 1C (FS) */
1.100 + CNTRL, /* 1D (GS) */
1.101 + CNTRL, /* 1E (RS) */
1.102 + CNTRL, /* 1F (US) */
1.103 + SPACE+BLANK, /* 20 SPACE */
1.104 + PUNCT, /* 21 ! */
1.105 + PUNCT, /* 22 " */
1.106 + PUNCT, /* 23 # */
1.107 + PUNCT, /* 24 $ */
1.108 + PUNCT, /* 25 % */
1.109 + PUNCT, /* 26 & */
1.110 + PUNCT, /* 27 ' */
1.111 + PUNCT, /* 28 ( */
1.112 + PUNCT, /* 29 ) */
1.113 + PUNCT, /* 2A * */
1.114 + PUNCT, /* 2B + */
1.115 + PUNCT, /* 2C , */
1.116 + PUNCT, /* 2D - */
1.117 + PUNCT, /* 2E . */
1.118 + PUNCT, /* 2F / */
1.119 + DIGIT+HEX+0, /* 30 0 */
1.120 + DIGIT+HEX+1, /* 31 1 */
1.121 + DIGIT+HEX+2, /* 32 2 */
1.122 + DIGIT+HEX+3, /* 33 3 */
1.123 + DIGIT+HEX+4, /* 34 4 */
1.124 + DIGIT+HEX+5, /* 35 5 */
1.125 + DIGIT+HEX+6, /* 36 6 */
1.126 + DIGIT+HEX+7, /* 37 7 */
1.127 + DIGIT+HEX+8, /* 38 8 */
1.128 + DIGIT+HEX+9, /* 39 9 */
1.129 + PUNCT, /* 3A : */
1.130 + PUNCT, /* 3B ; */
1.131 + PUNCT, /* 3C < */
1.132 + PUNCT, /* 3D = */
1.133 + PUNCT, /* 3E > */
1.134 + PUNCT, /* 3F ? */
1.135 + PUNCT, /* 40 @ */
1.136 + UPPER+HEX+10, /* 41 A */
1.137 + UPPER+HEX+11, /* 42 B */
1.138 + UPPER+HEX+12, /* 43 C */
1.139 + UPPER+HEX+13, /* 44 D */
1.140 + UPPER+HEX+14, /* 45 E */
1.141 + UPPER+HEX+15, /* 46 F */
1.142 + UPPER+16, /* 47 G */
1.143 + UPPER+17, /* 48 H */
1.144 + UPPER+18, /* 49 I */
1.145 + UPPER+19, /* 4A J */
1.146 + UPPER+20, /* 4B K */
1.147 + UPPER+21, /* 4C L */
1.148 + UPPER+22, /* 4D M */
1.149 + UPPER+23, /* 4E N */
1.150 + UPPER+24, /* 4F O */
1.151 + UPPER+25, /* 50 P */
1.152 + UPPER+26, /* 51 Q */
1.153 + UPPER+27, /* 52 R */
1.154 + UPPER+28, /* 53 S */
1.155 + UPPER+29, /* 54 T */
1.156 + UPPER+30, /* 55 U */
1.157 + UPPER+31, /* 56 V */
1.158 + UPPER+32, /* 57 W */
1.159 + UPPER+33, /* 58 X */
1.160 + UPPER+34, /* 59 Y */
1.161 + UPPER+35, /* 5A Z */
1.162 + PUNCT, /* 5B [ */
1.163 + PUNCT, /* 5C \ */
1.164 + PUNCT, /* 5D ] */
1.165 + PUNCT, /* 5E ^ */
1.166 + PUNCT|UNDER, /* 5F _ */
1.167 + PUNCT, /* 60 ` */
1.168 + LOWER+HEX+10, /* 61 a */
1.169 + LOWER+HEX+11, /* 62 b */
1.170 + LOWER+HEX+12, /* 63 c */
1.171 + LOWER+HEX+13, /* 64 d */
1.172 + LOWER+HEX+14, /* 65 e */
1.173 + LOWER+HEX+15, /* 66 f */
1.174 + LOWER+16, /* 67 g */
1.175 + LOWER+17, /* 68 h */
1.176 + LOWER+18, /* 69 i */
1.177 + LOWER+19, /* 6A j */
1.178 + LOWER+20, /* 6B k */
1.179 + LOWER+21, /* 6C l */
1.180 + LOWER+22, /* 6D m */
1.181 + LOWER+23, /* 6E n */
1.182 + LOWER+24, /* 6F o */
1.183 + LOWER+25, /* 70 p */
1.184 + LOWER+26, /* 71 q */
1.185 + LOWER+27, /* 72 r */
1.186 + LOWER+28, /* 73 s */
1.187 + LOWER+29, /* 74 t */
1.188 + LOWER+30, /* 75 u */
1.189 + LOWER+31, /* 76 v */
1.190 + LOWER+32, /* 77 w */
1.191 + LOWER+33, /* 78 x */
1.192 + LOWER+34, /* 79 y */
1.193 + LOWER+35, /* 7A z */
1.194 + PUNCT, /* 7B { */
1.195 + PUNCT, /* 7C | */
1.196 + PUNCT, /* 7D } */
1.197 + PUNCT, /* 7E ~ */
1.198 + CNTRL, /* 7F (DEL) */
1.199 + };
1.200 +
1.201 + static int getType(int ch) {
1.202 + return ((ch & 0xFFFFFF80) == 0 ? ctype[ch] : 0);
1.203 + }
1.204 +
1.205 + static boolean isType(int ch, int type) {
1.206 + return (getType(ch) & type) != 0;
1.207 + }
1.208 +
1.209 + static boolean isAscii(int ch) {
1.210 + return ((ch & 0xFFFFFF80) == 0);
1.211 + }
1.212 +
1.213 + static boolean isAlpha(int ch) {
1.214 + return isType(ch, ALPHA);
1.215 + }
1.216 +
1.217 + static boolean isDigit(int ch) {
1.218 + return ((ch-'0')|('9'-ch)) >= 0;
1.219 + }
1.220 +
1.221 + static boolean isAlnum(int ch) {
1.222 + return isType(ch, ALNUM);
1.223 + }
1.224 +
1.225 + static boolean isGraph(int ch) {
1.226 + return isType(ch, GRAPH);
1.227 + }
1.228 +
1.229 + static boolean isPrint(int ch) {
1.230 + return ((ch-0x20)|(0x7E-ch)) >= 0;
1.231 + }
1.232 +
1.233 + static boolean isPunct(int ch) {
1.234 + return isType(ch, PUNCT);
1.235 + }
1.236 +
1.237 + static boolean isSpace(int ch) {
1.238 + return isType(ch, SPACE);
1.239 + }
1.240 +
1.241 + static boolean isHexDigit(int ch) {
1.242 + return isType(ch, HEX);
1.243 + }
1.244 +
1.245 + static boolean isOctDigit(int ch) {
1.246 + return ((ch-'0')|('7'-ch)) >= 0;
1.247 + }
1.248 +
1.249 + static boolean isCntrl(int ch) {
1.250 + return isType(ch, CNTRL);
1.251 + }
1.252 +
1.253 + static boolean isLower(int ch) {
1.254 + return ((ch-'a')|('z'-ch)) >= 0;
1.255 + }
1.256 +
1.257 + static boolean isUpper(int ch) {
1.258 + return ((ch-'A')|('Z'-ch)) >= 0;
1.259 + }
1.260 +
1.261 + static boolean isWord(int ch) {
1.262 + return isType(ch, WORD);
1.263 + }
1.264 +
1.265 + static int toDigit(int ch) {
1.266 + return (ctype[ch & 0x7F] & 0x3F);
1.267 + }
1.268 +
1.269 + static int toLower(int ch) {
1.270 + return isUpper(ch) ? (ch + 0x20) : ch;
1.271 + }
1.272 +
1.273 + static int toUpper(int ch) {
1.274 + return isLower(ch) ? (ch - 0x20) : ch;
1.275 + }
1.276 +
1.277 +}
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/rt/emul/compact/src/main/java/java/util/regex/MatchResult.java Mon Oct 07 16:13:27 2013 +0200
2.3 @@ -0,0 +1,188 @@
2.4 +/*
2.5 + * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
2.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
2.7 + *
2.8 + * This code is free software; you can redistribute it and/or modify it
2.9 + * under the terms of the GNU General Public License version 2 only, as
2.10 + * published by the Free Software Foundation. Oracle designates this
2.11 + * particular file as subject to the "Classpath" exception as provided
2.12 + * by Oracle in the LICENSE file that accompanied this code.
2.13 + *
2.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
2.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
2.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
2.17 + * version 2 for more details (a copy is included in the LICENSE file that
2.18 + * accompanied this code).
2.19 + *
2.20 + * You should have received a copy of the GNU General Public License version
2.21 + * 2 along with this work; if not, write to the Free Software Foundation,
2.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
2.23 + *
2.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2.25 + * or visit www.oracle.com if you need additional information or have any
2.26 + * questions.
2.27 + */
2.28 +
2.29 +package java.util.regex;
2.30 +
2.31 +/**
2.32 + * The result of a match operation.
2.33 + *
2.34 + * <p>This interface contains query methods used to determine the
2.35 + * results of a match against a regular expression. The match boundaries,
2.36 + * groups and group boundaries can be seen but not modified through
2.37 + * a <code>MatchResult</code>.
2.38 + *
2.39 + * @author Michael McCloskey
2.40 + * @see Matcher
2.41 + * @since 1.5
2.42 + */
2.43 +public interface MatchResult {
2.44 +
2.45 + /**
2.46 + * Returns the start index of the match.
2.47 + *
2.48 + * @return The index of the first character matched
2.49 + *
2.50 + * @throws IllegalStateException
2.51 + * If no match has yet been attempted,
2.52 + * or if the previous match operation failed
2.53 + */
2.54 + public int start();
2.55 +
2.56 + /**
2.57 + * Returns the start index of the subsequence captured by the given group
2.58 + * during this match.
2.59 + *
2.60 + * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
2.61 + * to right, starting at one. Group zero denotes the entire pattern, so
2.62 + * the expression <i>m.</i><tt>start(0)</tt> is equivalent to
2.63 + * <i>m.</i><tt>start()</tt>. </p>
2.64 + *
2.65 + * @param group
2.66 + * The index of a capturing group in this matcher's pattern
2.67 + *
2.68 + * @return The index of the first character captured by the group,
2.69 + * or <tt>-1</tt> if the match was successful but the group
2.70 + * itself did not match anything
2.71 + *
2.72 + * @throws IllegalStateException
2.73 + * If no match has yet been attempted,
2.74 + * or if the previous match operation failed
2.75 + *
2.76 + * @throws IndexOutOfBoundsException
2.77 + * If there is no capturing group in the pattern
2.78 + * with the given index
2.79 + */
2.80 + public int start(int group);
2.81 +
2.82 + /**
2.83 + * Returns the offset after the last character matched. </p>
2.84 + *
2.85 + * @return @return The offset after the last character matched
2.86 + *
2.87 + * @throws IllegalStateException
2.88 + * If no match has yet been attempted,
2.89 + * or if the previous match operation failed
2.90 + */
2.91 + public int end();
2.92 +
2.93 + /**
2.94 + * Returns the offset after the last character of the subsequence
2.95 + * captured by the given group during this match.
2.96 + *
2.97 + * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
2.98 + * to right, starting at one. Group zero denotes the entire pattern, so
2.99 + * the expression <i>m.</i><tt>end(0)</tt> is equivalent to
2.100 + * <i>m.</i><tt>end()</tt>. </p>
2.101 + *
2.102 + * @param group
2.103 + * The index of a capturing group in this matcher's pattern
2.104 + *
2.105 + * @return The offset after the last character captured by the group,
2.106 + * or <tt>-1</tt> if the match was successful
2.107 + * but the group itself did not match anything
2.108 + *
2.109 + * @throws IllegalStateException
2.110 + * If no match has yet been attempted,
2.111 + * or if the previous match operation failed
2.112 + *
2.113 + * @throws IndexOutOfBoundsException
2.114 + * If there is no capturing group in the pattern
2.115 + * with the given index
2.116 + */
2.117 + public int end(int group);
2.118 +
2.119 + /**
2.120 + * Returns the input subsequence matched by the previous match.
2.121 + *
2.122 + * <p> For a matcher <i>m</i> with input sequence <i>s</i>,
2.123 + * the expressions <i>m.</i><tt>group()</tt> and
2.124 + * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(),</tt> <i>m.</i><tt>end())</tt>
2.125 + * are equivalent. </p>
2.126 + *
2.127 + * <p> Note that some patterns, for example <tt>a*</tt>, match the empty
2.128 + * string. This method will return the empty string when the pattern
2.129 + * successfully matches the empty string in the input. </p>
2.130 + *
2.131 + * @return The (possibly empty) subsequence matched by the previous match,
2.132 + * in string form
2.133 + *
2.134 + * @throws IllegalStateException
2.135 + * If no match has yet been attempted,
2.136 + * or if the previous match operation failed
2.137 + */
2.138 + public String group();
2.139 +
2.140 + /**
2.141 + * Returns the input subsequence captured by the given group during the
2.142 + * previous match operation.
2.143 + *
2.144 + * <p> For a matcher <i>m</i>, input sequence <i>s</i>, and group index
2.145 + * <i>g</i>, the expressions <i>m.</i><tt>group(</tt><i>g</i><tt>)</tt> and
2.146 + * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(</tt><i>g</i><tt>),</tt> <i>m.</i><tt>end(</tt><i>g</i><tt>))</tt>
2.147 + * are equivalent. </p>
2.148 + *
2.149 + * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
2.150 + * to right, starting at one. Group zero denotes the entire pattern, so
2.151 + * the expression <tt>m.group(0)</tt> is equivalent to <tt>m.group()</tt>.
2.152 + * </p>
2.153 + *
2.154 + * <p> If the match was successful but the group specified failed to match
2.155 + * any part of the input sequence, then <tt>null</tt> is returned. Note
2.156 + * that some groups, for example <tt>(a*)</tt>, match the empty string.
2.157 + * This method will return the empty string when such a group successfully
2.158 + * matches the empty string in the input. </p>
2.159 + *
2.160 + * @param group
2.161 + * The index of a capturing group in this matcher's pattern
2.162 + *
2.163 + * @return The (possibly empty) subsequence captured by the group
2.164 + * during the previous match, or <tt>null</tt> if the group
2.165 + * failed to match part of the input
2.166 + *
2.167 + * @throws IllegalStateException
2.168 + * If no match has yet been attempted,
2.169 + * or if the previous match operation failed
2.170 + *
2.171 + * @throws IndexOutOfBoundsException
2.172 + * If there is no capturing group in the pattern
2.173 + * with the given index
2.174 + */
2.175 + public String group(int group);
2.176 +
2.177 + /**
2.178 + * Returns the number of capturing groups in this match result's pattern.
2.179 + *
2.180 + * <p> Group zero denotes the entire pattern by convention. It is not
2.181 + * included in this count.
2.182 + *
2.183 + * <p> Any non-negative integer smaller than or equal to the value
2.184 + * returned by this method is guaranteed to be a valid group index for
2.185 + * this matcher. </p>
2.186 + *
2.187 + * @return The number of capturing groups in this matcher's pattern
2.188 + */
2.189 + public int groupCount();
2.190 +
2.191 +}
3.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
3.2 +++ b/rt/emul/compact/src/main/java/java/util/regex/Matcher.java Mon Oct 07 16:13:27 2013 +0200
3.3 @@ -0,0 +1,1256 @@
3.4 +/*
3.5 + * Copyright (c) 1999, 2009, Oracle and/or its affiliates. All rights reserved.
3.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3.7 + *
3.8 + * This code is free software; you can redistribute it and/or modify it
3.9 + * under the terms of the GNU General Public License version 2 only, as
3.10 + * published by the Free Software Foundation. Oracle designates this
3.11 + * particular file as subject to the "Classpath" exception as provided
3.12 + * by Oracle in the LICENSE file that accompanied this code.
3.13 + *
3.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
3.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
3.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
3.17 + * version 2 for more details (a copy is included in the LICENSE file that
3.18 + * accompanied this code).
3.19 + *
3.20 + * You should have received a copy of the GNU General Public License version
3.21 + * 2 along with this work; if not, write to the Free Software Foundation,
3.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
3.23 + *
3.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
3.25 + * or visit www.oracle.com if you need additional information or have any
3.26 + * questions.
3.27 + */
3.28 +
3.29 +package java.util.regex;
3.30 +
3.31 +
3.32 +/**
3.33 + * An engine that performs match operations on a {@link java.lang.CharSequence
3.34 + * </code>character sequence<code>} by interpreting a {@link Pattern}.
3.35 + *
3.36 + * <p> A matcher is created from a pattern by invoking the pattern's {@link
3.37 + * Pattern#matcher matcher} method. Once created, a matcher can be used to
3.38 + * perform three different kinds of match operations:
3.39 + *
3.40 + * <ul>
3.41 + *
3.42 + * <li><p> The {@link #matches matches} method attempts to match the entire
3.43 + * input sequence against the pattern. </p></li>
3.44 + *
3.45 + * <li><p> The {@link #lookingAt lookingAt} method attempts to match the
3.46 + * input sequence, starting at the beginning, against the pattern. </p></li>
3.47 + *
3.48 + * <li><p> The {@link #find find} method scans the input sequence looking for
3.49 + * the next subsequence that matches the pattern. </p></li>
3.50 + *
3.51 + * </ul>
3.52 + *
3.53 + * <p> Each of these methods returns a boolean indicating success or failure.
3.54 + * More information about a successful match can be obtained by querying the
3.55 + * state of the matcher.
3.56 + *
3.57 + * <p> A matcher finds matches in a subset of its input called the
3.58 + * <i>region</i>. By default, the region contains all of the matcher's input.
3.59 + * The region can be modified via the{@link #region region} method and queried
3.60 + * via the {@link #regionStart regionStart} and {@link #regionEnd regionEnd}
3.61 + * methods. The way that the region boundaries interact with some pattern
3.62 + * constructs can be changed. See {@link #useAnchoringBounds
3.63 + * useAnchoringBounds} and {@link #useTransparentBounds useTransparentBounds}
3.64 + * for more details.
3.65 + *
3.66 + * <p> This class also defines methods for replacing matched subsequences with
3.67 + * new strings whose contents can, if desired, be computed from the match
3.68 + * result. The {@link #appendReplacement appendReplacement} and {@link
3.69 + * #appendTail appendTail} methods can be used in tandem in order to collect
3.70 + * the result into an existing string buffer, or the more convenient {@link
3.71 + * #replaceAll replaceAll} method can be used to create a string in which every
3.72 + * matching subsequence in the input sequence is replaced.
3.73 + *
3.74 + * <p> The explicit state of a matcher includes the start and end indices of
3.75 + * the most recent successful match. It also includes the start and end
3.76 + * indices of the input subsequence captured by each <a
3.77 + * href="Pattern.html#cg">capturing group</a> in the pattern as well as a total
3.78 + * count of such subsequences. As a convenience, methods are also provided for
3.79 + * returning these captured subsequences in string form.
3.80 + *
3.81 + * <p> The explicit state of a matcher is initially undefined; attempting to
3.82 + * query any part of it before a successful match will cause an {@link
3.83 + * IllegalStateException} to be thrown. The explicit state of a matcher is
3.84 + * recomputed by every match operation.
3.85 + *
3.86 + * <p> The implicit state of a matcher includes the input character sequence as
3.87 + * well as the <i>append position</i>, which is initially zero and is updated
3.88 + * by the {@link #appendReplacement appendReplacement} method.
3.89 + *
3.90 + * <p> A matcher may be reset explicitly by invoking its {@link #reset()}
3.91 + * method or, if a new input sequence is desired, its {@link
3.92 + * #reset(java.lang.CharSequence) reset(CharSequence)} method. Resetting a
3.93 + * matcher discards its explicit state information and sets the append position
3.94 + * to zero.
3.95 + *
3.96 + * <p> Instances of this class are not safe for use by multiple concurrent
3.97 + * threads. </p>
3.98 + *
3.99 + *
3.100 + * @author Mike McCloskey
3.101 + * @author Mark Reinhold
3.102 + * @author JSR-51 Expert Group
3.103 + * @since 1.4
3.104 + * @spec JSR-51
3.105 + */
3.106 +
3.107 +public final class Matcher implements MatchResult {
3.108 +
3.109 + /**
3.110 + * The Pattern object that created this Matcher.
3.111 + */
3.112 + Pattern parentPattern;
3.113 +
3.114 + /**
3.115 + * The storage used by groups. They may contain invalid values if
3.116 + * a group was skipped during the matching.
3.117 + */
3.118 + int[] groups;
3.119 +
3.120 + /**
3.121 + * The range within the sequence that is to be matched. Anchors
3.122 + * will match at these "hard" boundaries. Changing the region
3.123 + * changes these values.
3.124 + */
3.125 + int from, to;
3.126 +
3.127 + /**
3.128 + * Lookbehind uses this value to ensure that the subexpression
3.129 + * match ends at the point where the lookbehind was encountered.
3.130 + */
3.131 + int lookbehindTo;
3.132 +
3.133 + /**
3.134 + * The original string being matched.
3.135 + */
3.136 + CharSequence text;
3.137 +
3.138 + /**
3.139 + * Matcher state used by the last node. NOANCHOR is used when a
3.140 + * match does not have to consume all of the input. ENDANCHOR is
3.141 + * the mode used for matching all the input.
3.142 + */
3.143 + static final int ENDANCHOR = 1;
3.144 + static final int NOANCHOR = 0;
3.145 + int acceptMode = NOANCHOR;
3.146 +
3.147 + /**
3.148 + * The range of string that last matched the pattern. If the last
3.149 + * match failed then first is -1; last initially holds 0 then it
3.150 + * holds the index of the end of the last match (which is where the
3.151 + * next search starts).
3.152 + */
3.153 + int first = -1, last = 0;
3.154 +
3.155 + /**
3.156 + * The end index of what matched in the last match operation.
3.157 + */
3.158 + int oldLast = -1;
3.159 +
3.160 + /**
3.161 + * The index of the last position appended in a substitution.
3.162 + */
3.163 + int lastAppendPosition = 0;
3.164 +
3.165 + /**
3.166 + * Storage used by nodes to tell what repetition they are on in
3.167 + * a pattern, and where groups begin. The nodes themselves are stateless,
3.168 + * so they rely on this field to hold state during a match.
3.169 + */
3.170 + int[] locals;
3.171 +
3.172 + /**
3.173 + * Boolean indicating whether or not more input could change
3.174 + * the results of the last match.
3.175 + *
3.176 + * If hitEnd is true, and a match was found, then more input
3.177 + * might cause a different match to be found.
3.178 + * If hitEnd is true and a match was not found, then more
3.179 + * input could cause a match to be found.
3.180 + * If hitEnd is false and a match was found, then more input
3.181 + * will not change the match.
3.182 + * If hitEnd is false and a match was not found, then more
3.183 + * input will not cause a match to be found.
3.184 + */
3.185 + boolean hitEnd;
3.186 +
3.187 + /**
3.188 + * Boolean indicating whether or not more input could change
3.189 + * a positive match into a negative one.
3.190 + *
3.191 + * If requireEnd is true, and a match was found, then more
3.192 + * input could cause the match to be lost.
3.193 + * If requireEnd is false and a match was found, then more
3.194 + * input might change the match but the match won't be lost.
3.195 + * If a match was not found, then requireEnd has no meaning.
3.196 + */
3.197 + boolean requireEnd;
3.198 +
3.199 + /**
3.200 + * If transparentBounds is true then the boundaries of this
3.201 + * matcher's region are transparent to lookahead, lookbehind,
3.202 + * and boundary matching constructs that try to see beyond them.
3.203 + */
3.204 + boolean transparentBounds = false;
3.205 +
3.206 + /**
3.207 + * If anchoringBounds is true then the boundaries of this
3.208 + * matcher's region match anchors such as ^ and $.
3.209 + */
3.210 + boolean anchoringBounds = true;
3.211 +
3.212 + /**
3.213 + * No default constructor.
3.214 + */
3.215 + Matcher() {
3.216 + }
3.217 +
3.218 + /**
3.219 + * All matchers have the state used by Pattern during a match.
3.220 + */
3.221 + Matcher(Pattern parent, CharSequence text) {
3.222 + this.parentPattern = parent;
3.223 + this.text = text;
3.224 +
3.225 + // Allocate state storage
3.226 + int parentGroupCount = Math.max(parent.capturingGroupCount, 10);
3.227 + groups = new int[parentGroupCount * 2];
3.228 + locals = new int[parent.localCount];
3.229 +
3.230 + // Put fields into initial states
3.231 + reset();
3.232 + }
3.233 +
3.234 + /**
3.235 + * Returns the pattern that is interpreted by this matcher.
3.236 + *
3.237 + * @return The pattern for which this matcher was created
3.238 + */
3.239 + public Pattern pattern() {
3.240 + return parentPattern;
3.241 + }
3.242 +
3.243 + /**
3.244 + * Returns the match state of this matcher as a {@link MatchResult}.
3.245 + * The result is unaffected by subsequent operations performed upon this
3.246 + * matcher.
3.247 + *
3.248 + * @return a <code>MatchResult</code> with the state of this matcher
3.249 + * @since 1.5
3.250 + */
3.251 + public MatchResult toMatchResult() {
3.252 + Matcher result = new Matcher(this.parentPattern, text.toString());
3.253 + result.first = this.first;
3.254 + result.last = this.last;
3.255 + result.groups = this.groups.clone();
3.256 + return result;
3.257 + }
3.258 +
3.259 + /**
3.260 + * Changes the <tt>Pattern</tt> that this <tt>Matcher</tt> uses to
3.261 + * find matches with.
3.262 + *
3.263 + * <p> This method causes this matcher to lose information
3.264 + * about the groups of the last match that occurred. The
3.265 + * matcher's position in the input is maintained and its
3.266 + * last append position is unaffected.</p>
3.267 + *
3.268 + * @param newPattern
3.269 + * The new pattern used by this matcher
3.270 + * @return This matcher
3.271 + * @throws IllegalArgumentException
3.272 + * If newPattern is <tt>null</tt>
3.273 + * @since 1.5
3.274 + */
3.275 + public Matcher usePattern(Pattern newPattern) {
3.276 + if (newPattern == null)
3.277 + throw new IllegalArgumentException("Pattern cannot be null");
3.278 + parentPattern = newPattern;
3.279 +
3.280 + // Reallocate state storage
3.281 + int parentGroupCount = Math.max(newPattern.capturingGroupCount, 10);
3.282 + groups = new int[parentGroupCount * 2];
3.283 + locals = new int[newPattern.localCount];
3.284 + for (int i = 0; i < groups.length; i++)
3.285 + groups[i] = -1;
3.286 + for (int i = 0; i < locals.length; i++)
3.287 + locals[i] = -1;
3.288 + return this;
3.289 + }
3.290 +
3.291 + /**
3.292 + * Resets this matcher.
3.293 + *
3.294 + * <p> Resetting a matcher discards all of its explicit state information
3.295 + * and sets its append position to zero. The matcher's region is set to the
3.296 + * default region, which is its entire character sequence. The anchoring
3.297 + * and transparency of this matcher's region boundaries are unaffected.
3.298 + *
3.299 + * @return This matcher
3.300 + */
3.301 + public Matcher reset() {
3.302 + first = -1;
3.303 + last = 0;
3.304 + oldLast = -1;
3.305 + for(int i=0; i<groups.length; i++)
3.306 + groups[i] = -1;
3.307 + for(int i=0; i<locals.length; i++)
3.308 + locals[i] = -1;
3.309 + lastAppendPosition = 0;
3.310 + from = 0;
3.311 + to = getTextLength();
3.312 + return this;
3.313 + }
3.314 +
3.315 + /**
3.316 + * Resets this matcher with a new input sequence.
3.317 + *
3.318 + * <p> Resetting a matcher discards all of its explicit state information
3.319 + * and sets its append position to zero. The matcher's region is set to
3.320 + * the default region, which is its entire character sequence. The
3.321 + * anchoring and transparency of this matcher's region boundaries are
3.322 + * unaffected.
3.323 + *
3.324 + * @param input
3.325 + * The new input character sequence
3.326 + *
3.327 + * @return This matcher
3.328 + */
3.329 + public Matcher reset(CharSequence input) {
3.330 + text = input;
3.331 + return reset();
3.332 + }
3.333 +
3.334 + /**
3.335 + * Returns the start index of the previous match. </p>
3.336 + *
3.337 + * @return The index of the first character matched
3.338 + *
3.339 + * @throws IllegalStateException
3.340 + * If no match has yet been attempted,
3.341 + * or if the previous match operation failed
3.342 + */
3.343 + public int start() {
3.344 + if (first < 0)
3.345 + throw new IllegalStateException("No match available");
3.346 + return first;
3.347 + }
3.348 +
3.349 + /**
3.350 + * Returns the start index of the subsequence captured by the given group
3.351 + * during the previous match operation.
3.352 + *
3.353 + * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
3.354 + * to right, starting at one. Group zero denotes the entire pattern, so
3.355 + * the expression <i>m.</i><tt>start(0)</tt> is equivalent to
3.356 + * <i>m.</i><tt>start()</tt>. </p>
3.357 + *
3.358 + * @param group
3.359 + * The index of a capturing group in this matcher's pattern
3.360 + *
3.361 + * @return The index of the first character captured by the group,
3.362 + * or <tt>-1</tt> if the match was successful but the group
3.363 + * itself did not match anything
3.364 + *
3.365 + * @throws IllegalStateException
3.366 + * If no match has yet been attempted,
3.367 + * or if the previous match operation failed
3.368 + *
3.369 + * @throws IndexOutOfBoundsException
3.370 + * If there is no capturing group in the pattern
3.371 + * with the given index
3.372 + */
3.373 + public int start(int group) {
3.374 + if (first < 0)
3.375 + throw new IllegalStateException("No match available");
3.376 + if (group > groupCount())
3.377 + throw new IndexOutOfBoundsException("No group " + group);
3.378 + return groups[group * 2];
3.379 + }
3.380 +
3.381 + /**
3.382 + * Returns the offset after the last character matched. </p>
3.383 + *
3.384 + * @return The offset after the last character matched
3.385 + *
3.386 + * @throws IllegalStateException
3.387 + * If no match has yet been attempted,
3.388 + * or if the previous match operation failed
3.389 + */
3.390 + public int end() {
3.391 + if (first < 0)
3.392 + throw new IllegalStateException("No match available");
3.393 + return last;
3.394 + }
3.395 +
3.396 + /**
3.397 + * Returns the offset after the last character of the subsequence
3.398 + * captured by the given group during the previous match operation.
3.399 + *
3.400 + * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
3.401 + * to right, starting at one. Group zero denotes the entire pattern, so
3.402 + * the expression <i>m.</i><tt>end(0)</tt> is equivalent to
3.403 + * <i>m.</i><tt>end()</tt>. </p>
3.404 + *
3.405 + * @param group
3.406 + * The index of a capturing group in this matcher's pattern
3.407 + *
3.408 + * @return The offset after the last character captured by the group,
3.409 + * or <tt>-1</tt> if the match was successful
3.410 + * but the group itself did not match anything
3.411 + *
3.412 + * @throws IllegalStateException
3.413 + * If no match has yet been attempted,
3.414 + * or if the previous match operation failed
3.415 + *
3.416 + * @throws IndexOutOfBoundsException
3.417 + * If there is no capturing group in the pattern
3.418 + * with the given index
3.419 + */
3.420 + public int end(int group) {
3.421 + if (first < 0)
3.422 + throw new IllegalStateException("No match available");
3.423 + if (group > groupCount())
3.424 + throw new IndexOutOfBoundsException("No group " + group);
3.425 + return groups[group * 2 + 1];
3.426 + }
3.427 +
3.428 + /**
3.429 + * Returns the input subsequence matched by the previous match.
3.430 + *
3.431 + * <p> For a matcher <i>m</i> with input sequence <i>s</i>,
3.432 + * the expressions <i>m.</i><tt>group()</tt> and
3.433 + * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(),</tt> <i>m.</i><tt>end())</tt>
3.434 + * are equivalent. </p>
3.435 + *
3.436 + * <p> Note that some patterns, for example <tt>a*</tt>, match the empty
3.437 + * string. This method will return the empty string when the pattern
3.438 + * successfully matches the empty string in the input. </p>
3.439 + *
3.440 + * @return The (possibly empty) subsequence matched by the previous match,
3.441 + * in string form
3.442 + *
3.443 + * @throws IllegalStateException
3.444 + * If no match has yet been attempted,
3.445 + * or if the previous match operation failed
3.446 + */
3.447 + public String group() {
3.448 + return group(0);
3.449 + }
3.450 +
3.451 + /**
3.452 + * Returns the input subsequence captured by the given group during the
3.453 + * previous match operation.
3.454 + *
3.455 + * <p> For a matcher <i>m</i>, input sequence <i>s</i>, and group index
3.456 + * <i>g</i>, the expressions <i>m.</i><tt>group(</tt><i>g</i><tt>)</tt> and
3.457 + * <i>s.</i><tt>substring(</tt><i>m.</i><tt>start(</tt><i>g</i><tt>),</tt> <i>m.</i><tt>end(</tt><i>g</i><tt>))</tt>
3.458 + * are equivalent. </p>
3.459 + *
3.460 + * <p> <a href="Pattern.html#cg">Capturing groups</a> are indexed from left
3.461 + * to right, starting at one. Group zero denotes the entire pattern, so
3.462 + * the expression <tt>m.group(0)</tt> is equivalent to <tt>m.group()</tt>.
3.463 + * </p>
3.464 + *
3.465 + * <p> If the match was successful but the group specified failed to match
3.466 + * any part of the input sequence, then <tt>null</tt> is returned. Note
3.467 + * that some groups, for example <tt>(a*)</tt>, match the empty string.
3.468 + * This method will return the empty string when such a group successfully
3.469 + * matches the empty string in the input. </p>
3.470 + *
3.471 + * @param group
3.472 + * The index of a capturing group in this matcher's pattern
3.473 + *
3.474 + * @return The (possibly empty) subsequence captured by the group
3.475 + * during the previous match, or <tt>null</tt> if the group
3.476 + * failed to match part of the input
3.477 + *
3.478 + * @throws IllegalStateException
3.479 + * If no match has yet been attempted,
3.480 + * or if the previous match operation failed
3.481 + *
3.482 + * @throws IndexOutOfBoundsException
3.483 + * If there is no capturing group in the pattern
3.484 + * with the given index
3.485 + */
3.486 + public String group(int group) {
3.487 + if (first < 0)
3.488 + throw new IllegalStateException("No match found");
3.489 + if (group < 0 || group > groupCount())
3.490 + throw new IndexOutOfBoundsException("No group " + group);
3.491 + if ((groups[group*2] == -1) || (groups[group*2+1] == -1))
3.492 + return null;
3.493 + return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString();
3.494 + }
3.495 +
3.496 + /**
3.497 + * Returns the input subsequence captured by the given
3.498 + * <a href="Pattern.html#groupname">named-capturing group</a> during the previous
3.499 + * match operation.
3.500 + *
3.501 + * <p> If the match was successful but the group specified failed to match
3.502 + * any part of the input sequence, then <tt>null</tt> is returned. Note
3.503 + * that some groups, for example <tt>(a*)</tt>, match the empty string.
3.504 + * This method will return the empty string when such a group successfully
3.505 + * matches the empty string in the input. </p>
3.506 + *
3.507 + * @param name
3.508 + * The name of a named-capturing group in this matcher's pattern
3.509 + *
3.510 + * @return The (possibly empty) subsequence captured by the named group
3.511 + * during the previous match, or <tt>null</tt> if the group
3.512 + * failed to match part of the input
3.513 + *
3.514 + * @throws IllegalStateException
3.515 + * If no match has yet been attempted,
3.516 + * or if the previous match operation failed
3.517 + *
3.518 + * @throws IllegalArgumentException
3.519 + * If there is no capturing group in the pattern
3.520 + * with the given name
3.521 + */
3.522 + public String group(String name) {
3.523 + if (name == null)
3.524 + throw new NullPointerException("Null group name");
3.525 + if (first < 0)
3.526 + throw new IllegalStateException("No match found");
3.527 + if (!parentPattern.namedGroups().containsKey(name))
3.528 + throw new IllegalArgumentException("No group with name <" + name + ">");
3.529 + int group = parentPattern.namedGroups().get(name);
3.530 + if ((groups[group*2] == -1) || (groups[group*2+1] == -1))
3.531 + return null;
3.532 + return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString();
3.533 + }
3.534 +
3.535 + /**
3.536 + * Returns the number of capturing groups in this matcher's pattern.
3.537 + *
3.538 + * <p> Group zero denotes the entire pattern by convention. It is not
3.539 + * included in this count.
3.540 + *
3.541 + * <p> Any non-negative integer smaller than or equal to the value
3.542 + * returned by this method is guaranteed to be a valid group index for
3.543 + * this matcher. </p>
3.544 + *
3.545 + * @return The number of capturing groups in this matcher's pattern
3.546 + */
3.547 + public int groupCount() {
3.548 + return parentPattern.capturingGroupCount - 1;
3.549 + }
3.550 +
3.551 + /**
3.552 + * Attempts to match the entire region against the pattern.
3.553 + *
3.554 + * <p> If the match succeeds then more information can be obtained via the
3.555 + * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p>
3.556 + *
3.557 + * @return <tt>true</tt> if, and only if, the entire region sequence
3.558 + * matches this matcher's pattern
3.559 + */
3.560 + public boolean matches() {
3.561 + return match(from, ENDANCHOR);
3.562 + }
3.563 +
3.564 + /**
3.565 + * Attempts to find the next subsequence of the input sequence that matches
3.566 + * the pattern.
3.567 + *
3.568 + * <p> This method starts at the beginning of this matcher's region, or, if
3.569 + * a previous invocation of the method was successful and the matcher has
3.570 + * not since been reset, at the first character not matched by the previous
3.571 + * match.
3.572 + *
3.573 + * <p> If the match succeeds then more information can be obtained via the
3.574 + * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p>
3.575 + *
3.576 + * @return <tt>true</tt> if, and only if, a subsequence of the input
3.577 + * sequence matches this matcher's pattern
3.578 + */
3.579 + public boolean find() {
3.580 + int nextSearchIndex = last;
3.581 + if (nextSearchIndex == first)
3.582 + nextSearchIndex++;
3.583 +
3.584 + // If next search starts before region, start it at region
3.585 + if (nextSearchIndex < from)
3.586 + nextSearchIndex = from;
3.587 +
3.588 + // If next search starts beyond region then it fails
3.589 + if (nextSearchIndex > to) {
3.590 + for (int i = 0; i < groups.length; i++)
3.591 + groups[i] = -1;
3.592 + return false;
3.593 + }
3.594 + return search(nextSearchIndex);
3.595 + }
3.596 +
3.597 + /**
3.598 + * Resets this matcher and then attempts to find the next subsequence of
3.599 + * the input sequence that matches the pattern, starting at the specified
3.600 + * index.
3.601 + *
3.602 + * <p> If the match succeeds then more information can be obtained via the
3.603 + * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods, and subsequent
3.604 + * invocations of the {@link #find()} method will start at the first
3.605 + * character not matched by this match. </p>
3.606 + *
3.607 + * @throws IndexOutOfBoundsException
3.608 + * If start is less than zero or if start is greater than the
3.609 + * length of the input sequence.
3.610 + *
3.611 + * @return <tt>true</tt> if, and only if, a subsequence of the input
3.612 + * sequence starting at the given index matches this matcher's
3.613 + * pattern
3.614 + */
3.615 + public boolean find(int start) {
3.616 + int limit = getTextLength();
3.617 + if ((start < 0) || (start > limit))
3.618 + throw new IndexOutOfBoundsException("Illegal start index");
3.619 + reset();
3.620 + return search(start);
3.621 + }
3.622 +
3.623 + /**
3.624 + * Attempts to match the input sequence, starting at the beginning of the
3.625 + * region, against the pattern.
3.626 + *
3.627 + * <p> Like the {@link #matches matches} method, this method always starts
3.628 + * at the beginning of the region; unlike that method, it does not
3.629 + * require that the entire region be matched.
3.630 + *
3.631 + * <p> If the match succeeds then more information can be obtained via the
3.632 + * <tt>start</tt>, <tt>end</tt>, and <tt>group</tt> methods. </p>
3.633 + *
3.634 + * @return <tt>true</tt> if, and only if, a prefix of the input
3.635 + * sequence matches this matcher's pattern
3.636 + */
3.637 + public boolean lookingAt() {
3.638 + return match(from, NOANCHOR);
3.639 + }
3.640 +
3.641 + /**
3.642 + * Returns a literal replacement <code>String</code> for the specified
3.643 + * <code>String</code>.
3.644 + *
3.645 + * This method produces a <code>String</code> that will work
3.646 + * as a literal replacement <code>s</code> in the
3.647 + * <code>appendReplacement</code> method of the {@link Matcher} class.
3.648 + * The <code>String</code> produced will match the sequence of characters
3.649 + * in <code>s</code> treated as a literal sequence. Slashes ('\') and
3.650 + * dollar signs ('$') will be given no special meaning.
3.651 + *
3.652 + * @param s The string to be literalized
3.653 + * @return A literal string replacement
3.654 + * @since 1.5
3.655 + */
3.656 + public static String quoteReplacement(String s) {
3.657 + if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1))
3.658 + return s;
3.659 + StringBuilder sb = new StringBuilder();
3.660 + for (int i=0; i<s.length(); i++) {
3.661 + char c = s.charAt(i);
3.662 + if (c == '\\' || c == '$') {
3.663 + sb.append('\\');
3.664 + }
3.665 + sb.append(c);
3.666 + }
3.667 + return sb.toString();
3.668 + }
3.669 +
3.670 + /**
3.671 + * Implements a non-terminal append-and-replace step.
3.672 + *
3.673 + * <p> This method performs the following actions: </p>
3.674 + *
3.675 + * <ol>
3.676 + *
3.677 + * <li><p> It reads characters from the input sequence, starting at the
3.678 + * append position, and appends them to the given string buffer. It
3.679 + * stops after reading the last character preceding the previous match,
3.680 + * that is, the character at index {@link
3.681 + * #start()} <tt>-</tt> <tt>1</tt>. </p></li>
3.682 + *
3.683 + * <li><p> It appends the given replacement string to the string buffer.
3.684 + * </p></li>
3.685 + *
3.686 + * <li><p> It sets the append position of this matcher to the index of
3.687 + * the last character matched, plus one, that is, to {@link #end()}.
3.688 + * </p></li>
3.689 + *
3.690 + * </ol>
3.691 + *
3.692 + * <p> The replacement string may contain references to subsequences
3.693 + * captured during the previous match: Each occurrence of
3.694 + * <tt>${</tt><i>name</i><tt>}</tt> or <tt>$</tt><i>g</i>
3.695 + * will be replaced by the result of evaluating the corresponding
3.696 + * {@link #group(String) group(name)} or {@link #group(int) group(g)</tt>}
3.697 + * respectively. For <tt>$</tt><i>g</i><tt></tt>,
3.698 + * the first number after the <tt>$</tt> is always treated as part of
3.699 + * the group reference. Subsequent numbers are incorporated into g if
3.700 + * they would form a legal group reference. Only the numerals '0'
3.701 + * through '9' are considered as potential components of the group
3.702 + * reference. If the second group matched the string <tt>"foo"</tt>, for
3.703 + * example, then passing the replacement string <tt>"$2bar"</tt> would
3.704 + * cause <tt>"foobar"</tt> to be appended to the string buffer. A dollar
3.705 + * sign (<tt>$</tt>) may be included as a literal in the replacement
3.706 + * string by preceding it with a backslash (<tt>\$</tt>).
3.707 + *
3.708 + * <p> Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in
3.709 + * the replacement string may cause the results to be different than if it
3.710 + * were being treated as a literal replacement string. Dollar signs may be
3.711 + * treated as references to captured subsequences as described above, and
3.712 + * backslashes are used to escape literal characters in the replacement
3.713 + * string.
3.714 + *
3.715 + * <p> This method is intended to be used in a loop together with the
3.716 + * {@link #appendTail appendTail} and {@link #find find} methods. The
3.717 + * following code, for example, writes <tt>one dog two dogs in the
3.718 + * yard</tt> to the standard-output stream: </p>
3.719 + *
3.720 + * <blockquote><pre>
3.721 + * Pattern p = Pattern.compile("cat");
3.722 + * Matcher m = p.matcher("one cat two cats in the yard");
3.723 + * StringBuffer sb = new StringBuffer();
3.724 + * while (m.find()) {
3.725 + * m.appendReplacement(sb, "dog");
3.726 + * }
3.727 + * m.appendTail(sb);
3.728 + * System.out.println(sb.toString());</pre></blockquote>
3.729 + *
3.730 + * @param sb
3.731 + * The target string buffer
3.732 + *
3.733 + * @param replacement
3.734 + * The replacement string
3.735 + *
3.736 + * @return This matcher
3.737 + *
3.738 + * @throws IllegalStateException
3.739 + * If no match has yet been attempted,
3.740 + * or if the previous match operation failed
3.741 + *
3.742 + * @throws IllegalArgumentException
3.743 + * If the replacement string refers to a named-capturing
3.744 + * group that does not exist in the pattern
3.745 + *
3.746 + * @throws IndexOutOfBoundsException
3.747 + * If the replacement string refers to a capturing group
3.748 + * that does not exist in the pattern
3.749 + */
3.750 + public Matcher appendReplacement(StringBuffer sb, String replacement) {
3.751 +
3.752 + // If no match, return error
3.753 + if (first < 0)
3.754 + throw new IllegalStateException("No match available");
3.755 +
3.756 + // Process substitution string to replace group references with groups
3.757 + int cursor = 0;
3.758 + StringBuilder result = new StringBuilder();
3.759 +
3.760 + while (cursor < replacement.length()) {
3.761 + char nextChar = replacement.charAt(cursor);
3.762 + if (nextChar == '\\') {
3.763 + cursor++;
3.764 + nextChar = replacement.charAt(cursor);
3.765 + result.append(nextChar);
3.766 + cursor++;
3.767 + } else if (nextChar == '$') {
3.768 + // Skip past $
3.769 + cursor++;
3.770 + // A StringIndexOutOfBoundsException is thrown if
3.771 + // this "$" is the last character in replacement
3.772 + // string in current implementation, a IAE might be
3.773 + // more appropriate.
3.774 + nextChar = replacement.charAt(cursor);
3.775 + int refNum = -1;
3.776 + if (nextChar == '{') {
3.777 + cursor++;
3.778 + StringBuilder gsb = new StringBuilder();
3.779 + while (cursor < replacement.length()) {
3.780 + nextChar = replacement.charAt(cursor);
3.781 + if (ASCII.isLower(nextChar) ||
3.782 + ASCII.isUpper(nextChar) ||
3.783 + ASCII.isDigit(nextChar)) {
3.784 + gsb.append(nextChar);
3.785 + cursor++;
3.786 + } else {
3.787 + break;
3.788 + }
3.789 + }
3.790 + if (gsb.length() == 0)
3.791 + throw new IllegalArgumentException(
3.792 + "named capturing group has 0 length name");
3.793 + if (nextChar != '}')
3.794 + throw new IllegalArgumentException(
3.795 + "named capturing group is missing trailing '}'");
3.796 + String gname = gsb.toString();
3.797 + if (ASCII.isDigit(gname.charAt(0)))
3.798 + throw new IllegalArgumentException(
3.799 + "capturing group name {" + gname +
3.800 + "} starts with digit character");
3.801 + if (!parentPattern.namedGroups().containsKey(gname))
3.802 + throw new IllegalArgumentException(
3.803 + "No group with name {" + gname + "}");
3.804 + refNum = parentPattern.namedGroups().get(gname);
3.805 + cursor++;
3.806 + } else {
3.807 + // The first number is always a group
3.808 + refNum = (int)nextChar - '0';
3.809 + if ((refNum < 0)||(refNum > 9))
3.810 + throw new IllegalArgumentException(
3.811 + "Illegal group reference");
3.812 + cursor++;
3.813 + // Capture the largest legal group string
3.814 + boolean done = false;
3.815 + while (!done) {
3.816 + if (cursor >= replacement.length()) {
3.817 + break;
3.818 + }
3.819 + int nextDigit = replacement.charAt(cursor) - '0';
3.820 + if ((nextDigit < 0)||(nextDigit > 9)) { // not a number
3.821 + break;
3.822 + }
3.823 + int newRefNum = (refNum * 10) + nextDigit;
3.824 + if (groupCount() < newRefNum) {
3.825 + done = true;
3.826 + } else {
3.827 + refNum = newRefNum;
3.828 + cursor++;
3.829 + }
3.830 + }
3.831 + }
3.832 + // Append group
3.833 + if (start(refNum) != -1 && end(refNum) != -1)
3.834 + result.append(text, start(refNum), end(refNum));
3.835 + } else {
3.836 + result.append(nextChar);
3.837 + cursor++;
3.838 + }
3.839 + }
3.840 + // Append the intervening text
3.841 + sb.append(text, lastAppendPosition, first);
3.842 + // Append the match substitution
3.843 + sb.append(result);
3.844 +
3.845 + lastAppendPosition = last;
3.846 + return this;
3.847 + }
3.848 +
3.849 + /**
3.850 + * Implements a terminal append-and-replace step.
3.851 + *
3.852 + * <p> This method reads characters from the input sequence, starting at
3.853 + * the append position, and appends them to the given string buffer. It is
3.854 + * intended to be invoked after one or more invocations of the {@link
3.855 + * #appendReplacement appendReplacement} method in order to copy the
3.856 + * remainder of the input sequence. </p>
3.857 + *
3.858 + * @param sb
3.859 + * The target string buffer
3.860 + *
3.861 + * @return The target string buffer
3.862 + */
3.863 + public StringBuffer appendTail(StringBuffer sb) {
3.864 + sb.append(text, lastAppendPosition, getTextLength());
3.865 + return sb;
3.866 + }
3.867 +
3.868 + /**
3.869 + * Replaces every subsequence of the input sequence that matches the
3.870 + * pattern with the given replacement string.
3.871 + *
3.872 + * <p> This method first resets this matcher. It then scans the input
3.873 + * sequence looking for matches of the pattern. Characters that are not
3.874 + * part of any match are appended directly to the result string; each match
3.875 + * is replaced in the result by the replacement string. The replacement
3.876 + * string may contain references to captured subsequences as in the {@link
3.877 + * #appendReplacement appendReplacement} method.
3.878 + *
3.879 + * <p> Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in
3.880 + * the replacement string may cause the results to be different than if it
3.881 + * were being treated as a literal replacement string. Dollar signs may be
3.882 + * treated as references to captured subsequences as described above, and
3.883 + * backslashes are used to escape literal characters in the replacement
3.884 + * string.
3.885 + *
3.886 + * <p> Given the regular expression <tt>a*b</tt>, the input
3.887 + * <tt>"aabfooaabfooabfoob"</tt>, and the replacement string
3.888 + * <tt>"-"</tt>, an invocation of this method on a matcher for that
3.889 + * expression would yield the string <tt>"-foo-foo-foo-"</tt>.
3.890 + *
3.891 + * <p> Invoking this method changes this matcher's state. If the matcher
3.892 + * is to be used in further matching operations then it should first be
3.893 + * reset. </p>
3.894 + *
3.895 + * @param replacement
3.896 + * The replacement string
3.897 + *
3.898 + * @return The string constructed by replacing each matching subsequence
3.899 + * by the replacement string, substituting captured subsequences
3.900 + * as needed
3.901 + */
3.902 + public String replaceAll(String replacement) {
3.903 + reset();
3.904 + boolean result = find();
3.905 + if (result) {
3.906 + StringBuffer sb = new StringBuffer();
3.907 + do {
3.908 + appendReplacement(sb, replacement);
3.909 + result = find();
3.910 + } while (result);
3.911 + appendTail(sb);
3.912 + return sb.toString();
3.913 + }
3.914 + return text.toString();
3.915 + }
3.916 +
3.917 + /**
3.918 + * Replaces the first subsequence of the input sequence that matches the
3.919 + * pattern with the given replacement string.
3.920 + *
3.921 + * <p> This method first resets this matcher. It then scans the input
3.922 + * sequence looking for a match of the pattern. Characters that are not
3.923 + * part of the match are appended directly to the result string; the match
3.924 + * is replaced in the result by the replacement string. The replacement
3.925 + * string may contain references to captured subsequences as in the {@link
3.926 + * #appendReplacement appendReplacement} method.
3.927 + *
3.928 + * <p>Note that backslashes (<tt>\</tt>) and dollar signs (<tt>$</tt>) in
3.929 + * the replacement string may cause the results to be different than if it
3.930 + * were being treated as a literal replacement string. Dollar signs may be
3.931 + * treated as references to captured subsequences as described above, and
3.932 + * backslashes are used to escape literal characters in the replacement
3.933 + * string.
3.934 + *
3.935 + * <p> Given the regular expression <tt>dog</tt>, the input
3.936 + * <tt>"zzzdogzzzdogzzz"</tt>, and the replacement string
3.937 + * <tt>"cat"</tt>, an invocation of this method on a matcher for that
3.938 + * expression would yield the string <tt>"zzzcatzzzdogzzz"</tt>. </p>
3.939 + *
3.940 + * <p> Invoking this method changes this matcher's state. If the matcher
3.941 + * is to be used in further matching operations then it should first be
3.942 + * reset. </p>
3.943 + *
3.944 + * @param replacement
3.945 + * The replacement string
3.946 + * @return The string constructed by replacing the first matching
3.947 + * subsequence by the replacement string, substituting captured
3.948 + * subsequences as needed
3.949 + */
3.950 + public String replaceFirst(String replacement) {
3.951 + if (replacement == null)
3.952 + throw new NullPointerException("replacement");
3.953 + reset();
3.954 + if (!find())
3.955 + return text.toString();
3.956 + StringBuffer sb = new StringBuffer();
3.957 + appendReplacement(sb, replacement);
3.958 + appendTail(sb);
3.959 + return sb.toString();
3.960 + }
3.961 +
3.962 + /**
3.963 + * Sets the limits of this matcher's region. The region is the part of the
3.964 + * input sequence that will be searched to find a match. Invoking this
3.965 + * method resets the matcher, and then sets the region to start at the
3.966 + * index specified by the <code>start</code> parameter and end at the
3.967 + * index specified by the <code>end</code> parameter.
3.968 + *
3.969 + * <p>Depending on the transparency and anchoring being used (see
3.970 + * {@link #useTransparentBounds useTransparentBounds} and
3.971 + * {@link #useAnchoringBounds useAnchoringBounds}), certain constructs such
3.972 + * as anchors may behave differently at or around the boundaries of the
3.973 + * region.
3.974 + *
3.975 + * @param start
3.976 + * The index to start searching at (inclusive)
3.977 + * @param end
3.978 + * The index to end searching at (exclusive)
3.979 + * @throws IndexOutOfBoundsException
3.980 + * If start or end is less than zero, if
3.981 + * start is greater than the length of the input sequence, if
3.982 + * end is greater than the length of the input sequence, or if
3.983 + * start is greater than end.
3.984 + * @return this matcher
3.985 + * @since 1.5
3.986 + */
3.987 + public Matcher region(int start, int end) {
3.988 + if ((start < 0) || (start > getTextLength()))
3.989 + throw new IndexOutOfBoundsException("start");
3.990 + if ((end < 0) || (end > getTextLength()))
3.991 + throw new IndexOutOfBoundsException("end");
3.992 + if (start > end)
3.993 + throw new IndexOutOfBoundsException("start > end");
3.994 + reset();
3.995 + from = start;
3.996 + to = end;
3.997 + return this;
3.998 + }
3.999 +
3.1000 + /**
3.1001 + * Reports the start index of this matcher's region. The
3.1002 + * searches this matcher conducts are limited to finding matches
3.1003 + * within {@link #regionStart regionStart} (inclusive) and
3.1004 + * {@link #regionEnd regionEnd} (exclusive).
3.1005 + *
3.1006 + * @return The starting point of this matcher's region
3.1007 + * @since 1.5
3.1008 + */
3.1009 + public int regionStart() {
3.1010 + return from;
3.1011 + }
3.1012 +
3.1013 + /**
3.1014 + * Reports the end index (exclusive) of this matcher's region.
3.1015 + * The searches this matcher conducts are limited to finding matches
3.1016 + * within {@link #regionStart regionStart} (inclusive) and
3.1017 + * {@link #regionEnd regionEnd} (exclusive).
3.1018 + *
3.1019 + * @return the ending point of this matcher's region
3.1020 + * @since 1.5
3.1021 + */
3.1022 + public int regionEnd() {
3.1023 + return to;
3.1024 + }
3.1025 +
3.1026 + /**
3.1027 + * Queries the transparency of region bounds for this matcher.
3.1028 + *
3.1029 + * <p> This method returns <tt>true</tt> if this matcher uses
3.1030 + * <i>transparent</i> bounds, <tt>false</tt> if it uses <i>opaque</i>
3.1031 + * bounds.
3.1032 + *
3.1033 + * <p> See {@link #useTransparentBounds useTransparentBounds} for a
3.1034 + * description of transparent and opaque bounds.
3.1035 + *
3.1036 + * <p> By default, a matcher uses opaque region boundaries.
3.1037 + *
3.1038 + * @return <tt>true</tt> iff this matcher is using transparent bounds,
3.1039 + * <tt>false</tt> otherwise.
3.1040 + * @see java.util.regex.Matcher#useTransparentBounds(boolean)
3.1041 + * @since 1.5
3.1042 + */
3.1043 + public boolean hasTransparentBounds() {
3.1044 + return transparentBounds;
3.1045 + }
3.1046 +
3.1047 + /**
3.1048 + * Sets the transparency of region bounds for this matcher.
3.1049 + *
3.1050 + * <p> Invoking this method with an argument of <tt>true</tt> will set this
3.1051 + * matcher to use <i>transparent</i> bounds. If the boolean
3.1052 + * argument is <tt>false</tt>, then <i>opaque</i> bounds will be used.
3.1053 + *
3.1054 + * <p> Using transparent bounds, the boundaries of this
3.1055 + * matcher's region are transparent to lookahead, lookbehind,
3.1056 + * and boundary matching constructs. Those constructs can see beyond the
3.1057 + * boundaries of the region to see if a match is appropriate.
3.1058 + *
3.1059 + * <p> Using opaque bounds, the boundaries of this matcher's
3.1060 + * region are opaque to lookahead, lookbehind, and boundary matching
3.1061 + * constructs that may try to see beyond them. Those constructs cannot
3.1062 + * look past the boundaries so they will fail to match anything outside
3.1063 + * of the region.
3.1064 + *
3.1065 + * <p> By default, a matcher uses opaque bounds.
3.1066 + *
3.1067 + * @param b a boolean indicating whether to use opaque or transparent
3.1068 + * regions
3.1069 + * @return this matcher
3.1070 + * @see java.util.regex.Matcher#hasTransparentBounds
3.1071 + * @since 1.5
3.1072 + */
3.1073 + public Matcher useTransparentBounds(boolean b) {
3.1074 + transparentBounds = b;
3.1075 + return this;
3.1076 + }
3.1077 +
3.1078 + /**
3.1079 + * Queries the anchoring of region bounds for this matcher.
3.1080 + *
3.1081 + * <p> This method returns <tt>true</tt> if this matcher uses
3.1082 + * <i>anchoring</i> bounds, <tt>false</tt> otherwise.
3.1083 + *
3.1084 + * <p> See {@link #useAnchoringBounds useAnchoringBounds} for a
3.1085 + * description of anchoring bounds.
3.1086 + *
3.1087 + * <p> By default, a matcher uses anchoring region boundaries.
3.1088 + *
3.1089 + * @return <tt>true</tt> iff this matcher is using anchoring bounds,
3.1090 + * <tt>false</tt> otherwise.
3.1091 + * @see java.util.regex.Matcher#useAnchoringBounds(boolean)
3.1092 + * @since 1.5
3.1093 + */
3.1094 + public boolean hasAnchoringBounds() {
3.1095 + return anchoringBounds;
3.1096 + }
3.1097 +
3.1098 + /**
3.1099 + * Sets the anchoring of region bounds for this matcher.
3.1100 + *
3.1101 + * <p> Invoking this method with an argument of <tt>true</tt> will set this
3.1102 + * matcher to use <i>anchoring</i> bounds. If the boolean
3.1103 + * argument is <tt>false</tt>, then <i>non-anchoring</i> bounds will be
3.1104 + * used.
3.1105 + *
3.1106 + * <p> Using anchoring bounds, the boundaries of this
3.1107 + * matcher's region match anchors such as ^ and $.
3.1108 + *
3.1109 + * <p> Without anchoring bounds, the boundaries of this
3.1110 + * matcher's region will not match anchors such as ^ and $.
3.1111 + *
3.1112 + * <p> By default, a matcher uses anchoring region boundaries.
3.1113 + *
3.1114 + * @param b a boolean indicating whether or not to use anchoring bounds.
3.1115 + * @return this matcher
3.1116 + * @see java.util.regex.Matcher#hasAnchoringBounds
3.1117 + * @since 1.5
3.1118 + */
3.1119 + public Matcher useAnchoringBounds(boolean b) {
3.1120 + anchoringBounds = b;
3.1121 + return this;
3.1122 + }
3.1123 +
3.1124 + /**
3.1125 + * <p>Returns the string representation of this matcher. The
3.1126 + * string representation of a <code>Matcher</code> contains information
3.1127 + * that may be useful for debugging. The exact format is unspecified.
3.1128 + *
3.1129 + * @return The string representation of this matcher
3.1130 + * @since 1.5
3.1131 + */
3.1132 + public String toString() {
3.1133 + StringBuilder sb = new StringBuilder();
3.1134 + sb.append("java.util.regex.Matcher");
3.1135 + sb.append("[pattern=" + pattern());
3.1136 + sb.append(" region=");
3.1137 + sb.append(regionStart() + "," + regionEnd());
3.1138 + sb.append(" lastmatch=");
3.1139 + if ((first >= 0) && (group() != null)) {
3.1140 + sb.append(group());
3.1141 + }
3.1142 + sb.append("]");
3.1143 + return sb.toString();
3.1144 + }
3.1145 +
3.1146 + /**
3.1147 + * <p>Returns true if the end of input was hit by the search engine in
3.1148 + * the last match operation performed by this matcher.
3.1149 + *
3.1150 + * <p>When this method returns true, then it is possible that more input
3.1151 + * would have changed the result of the last search.
3.1152 + *
3.1153 + * @return true iff the end of input was hit in the last match; false
3.1154 + * otherwise
3.1155 + * @since 1.5
3.1156 + */
3.1157 + public boolean hitEnd() {
3.1158 + return hitEnd;
3.1159 + }
3.1160 +
3.1161 + /**
3.1162 + * <p>Returns true if more input could change a positive match into a
3.1163 + * negative one.
3.1164 + *
3.1165 + * <p>If this method returns true, and a match was found, then more
3.1166 + * input could cause the match to be lost. If this method returns false
3.1167 + * and a match was found, then more input might change the match but the
3.1168 + * match won't be lost. If a match was not found, then requireEnd has no
3.1169 + * meaning.
3.1170 + *
3.1171 + * @return true iff more input could change a positive match into a
3.1172 + * negative one.
3.1173 + * @since 1.5
3.1174 + */
3.1175 + public boolean requireEnd() {
3.1176 + return requireEnd;
3.1177 + }
3.1178 +
3.1179 + /**
3.1180 + * Initiates a search to find a Pattern within the given bounds.
3.1181 + * The groups are filled with default values and the match of the root
3.1182 + * of the state machine is called. The state machine will hold the state
3.1183 + * of the match as it proceeds in this matcher.
3.1184 + *
3.1185 + * Matcher.from is not set here, because it is the "hard" boundary
3.1186 + * of the start of the search which anchors will set to. The from param
3.1187 + * is the "soft" boundary of the start of the search, meaning that the
3.1188 + * regex tries to match at that index but ^ won't match there. Subsequent
3.1189 + * calls to the search methods start at a new "soft" boundary which is
3.1190 + * the end of the previous match.
3.1191 + */
3.1192 + boolean search(int from) {
3.1193 + this.hitEnd = false;
3.1194 + this.requireEnd = false;
3.1195 + from = from < 0 ? 0 : from;
3.1196 + this.first = from;
3.1197 + this.oldLast = oldLast < 0 ? from : oldLast;
3.1198 + for (int i = 0; i < groups.length; i++)
3.1199 + groups[i] = -1;
3.1200 + acceptMode = NOANCHOR;
3.1201 + boolean result = parentPattern.root.match(this, from, text);
3.1202 + if (!result)
3.1203 + this.first = -1;
3.1204 + this.oldLast = this.last;
3.1205 + return result;
3.1206 + }
3.1207 +
3.1208 + /**
3.1209 + * Initiates a search for an anchored match to a Pattern within the given
3.1210 + * bounds. The groups are filled with default values and the match of the
3.1211 + * root of the state machine is called. The state machine will hold the
3.1212 + * state of the match as it proceeds in this matcher.
3.1213 + */
3.1214 + boolean match(int from, int anchor) {
3.1215 + this.hitEnd = false;
3.1216 + this.requireEnd = false;
3.1217 + from = from < 0 ? 0 : from;
3.1218 + this.first = from;
3.1219 + this.oldLast = oldLast < 0 ? from : oldLast;
3.1220 + for (int i = 0; i < groups.length; i++)
3.1221 + groups[i] = -1;
3.1222 + acceptMode = anchor;
3.1223 + boolean result = parentPattern.matchRoot.match(this, from, text);
3.1224 + if (!result)
3.1225 + this.first = -1;
3.1226 + this.oldLast = this.last;
3.1227 + return result;
3.1228 + }
3.1229 +
3.1230 + /**
3.1231 + * Returns the end index of the text.
3.1232 + *
3.1233 + * @return the index after the last character in the text
3.1234 + */
3.1235 + int getTextLength() {
3.1236 + return text.length();
3.1237 + }
3.1238 +
3.1239 + /**
3.1240 + * Generates a String from this Matcher's input in the specified range.
3.1241 + *
3.1242 + * @param beginIndex the beginning index, inclusive
3.1243 + * @param endIndex the ending index, exclusive
3.1244 + * @return A String generated from this Matcher's input
3.1245 + */
3.1246 + CharSequence getSubSequence(int beginIndex, int endIndex) {
3.1247 + return text.subSequence(beginIndex, endIndex);
3.1248 + }
3.1249 +
3.1250 + /**
3.1251 + * Returns this Matcher's input character at index i.
3.1252 + *
3.1253 + * @return A char from the specified index
3.1254 + */
3.1255 + char charAt(int i) {
3.1256 + return text.charAt(i);
3.1257 + }
3.1258 +
3.1259 +}
4.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
4.2 +++ b/rt/emul/compact/src/main/java/java/util/regex/Pattern.java Mon Oct 07 16:13:27 2013 +0200
4.3 @@ -0,0 +1,5648 @@
4.4 +/*
4.5 + * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
4.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4.7 + *
4.8 + * This code is free software; you can redistribute it and/or modify it
4.9 + * under the terms of the GNU General Public License version 2 only, as
4.10 + * published by the Free Software Foundation. Oracle designates this
4.11 + * particular file as subject to the "Classpath" exception as provided
4.12 + * by Oracle in the LICENSE file that accompanied this code.
4.13 + *
4.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
4.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
4.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
4.17 + * version 2 for more details (a copy is included in the LICENSE file that
4.18 + * accompanied this code).
4.19 + *
4.20 + * You should have received a copy of the GNU General Public License version
4.21 + * 2 along with this work; if not, write to the Free Software Foundation,
4.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
4.23 + *
4.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
4.25 + * or visit www.oracle.com if you need additional information or have any
4.26 + * questions.
4.27 + */
4.28 +
4.29 +package java.util.regex;
4.30 +
4.31 +import java.security.AccessController;
4.32 +import java.security.PrivilegedAction;
4.33 +import java.text.CharacterIterator;
4.34 +import java.text.Normalizer;
4.35 +import java.util.Locale;
4.36 +import java.util.Map;
4.37 +import java.util.ArrayList;
4.38 +import java.util.HashMap;
4.39 +import java.util.Arrays;
4.40 +
4.41 +
4.42 +/**
4.43 + * A compiled representation of a regular expression.
4.44 + *
4.45 + * <p> A regular expression, specified as a string, must first be compiled into
4.46 + * an instance of this class. The resulting pattern can then be used to create
4.47 + * a {@link Matcher} object that can match arbitrary {@link
4.48 + * java.lang.CharSequence </code>character sequences<code>} against the regular
4.49 + * expression. All of the state involved in performing a match resides in the
4.50 + * matcher, so many matchers can share the same pattern.
4.51 + *
4.52 + * <p> A typical invocation sequence is thus
4.53 + *
4.54 + * <blockquote><pre>
4.55 + * Pattern p = Pattern.{@link #compile compile}("a*b");
4.56 + * Matcher m = p.{@link #matcher matcher}("aaaaab");
4.57 + * boolean b = m.{@link Matcher#matches matches}();</pre></blockquote>
4.58 + *
4.59 + * <p> A {@link #matches matches} method is defined by this class as a
4.60 + * convenience for when a regular expression is used just once. This method
4.61 + * compiles an expression and matches an input sequence against it in a single
4.62 + * invocation. The statement
4.63 + *
4.64 + * <blockquote><pre>
4.65 + * boolean b = Pattern.matches("a*b", "aaaaab");</pre></blockquote>
4.66 + *
4.67 + * is equivalent to the three statements above, though for repeated matches it
4.68 + * is less efficient since it does not allow the compiled pattern to be reused.
4.69 + *
4.70 + * <p> Instances of this class are immutable and are safe for use by multiple
4.71 + * concurrent threads. Instances of the {@link Matcher} class are not safe for
4.72 + * such use.
4.73 + *
4.74 + *
4.75 + * <a name="sum">
4.76 + * <h4> Summary of regular-expression constructs </h4>
4.77 + *
4.78 + * <table border="0" cellpadding="1" cellspacing="0"
4.79 + * summary="Regular expression constructs, and what they match">
4.80 + *
4.81 + * <tr align="left">
4.82 + * <th bgcolor="#CCCCFF" align="left" id="construct">Construct</th>
4.83 + * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th>
4.84 + * </tr>
4.85 + *
4.86 + * <tr><th> </th></tr>
4.87 + * <tr align="left"><th colspan="2" id="characters">Characters</th></tr>
4.88 + *
4.89 + * <tr><td valign="top" headers="construct characters"><i>x</i></td>
4.90 + * <td headers="matches">The character <i>x</i></td></tr>
4.91 + * <tr><td valign="top" headers="construct characters"><tt>\\</tt></td>
4.92 + * <td headers="matches">The backslash character</td></tr>
4.93 + * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>n</i></td>
4.94 + * <td headers="matches">The character with octal value <tt>0</tt><i>n</i>
4.95 + * (0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
4.96 + * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>nn</i></td>
4.97 + * <td headers="matches">The character with octal value <tt>0</tt><i>nn</i>
4.98 + * (0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
4.99 + * <tr><td valign="top" headers="construct characters"><tt>\0</tt><i>mnn</i></td>
4.100 + * <td headers="matches">The character with octal value <tt>0</tt><i>mnn</i>
4.101 + * (0 <tt><=</tt> <i>m</i> <tt><=</tt> 3,
4.102 + * 0 <tt><=</tt> <i>n</i> <tt><=</tt> 7)</td></tr>
4.103 + * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>hh</i></td>
4.104 + * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>hh</i></td></tr>
4.105 + * <tr><td valign="top" headers="construct characters"><tt>\u</tt><i>hhhh</i></td>
4.106 + * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>hhhh</i></td></tr>
4.107 + * <tr><td valign="top" headers="construct characters"><tt>\x</tt><i>{h...h}</i></td>
4.108 + * <td headers="matches">The character with hexadecimal value <tt>0x</tt><i>h...h</i>
4.109 + * ({@link java.lang.Character#MIN_CODE_POINT Character.MIN_CODE_POINT}
4.110 + * <= <tt>0x</tt><i>h...h</i> <= 
4.111 + * {@link java.lang.Character#MAX_CODE_POINT Character.MAX_CODE_POINT})</td></tr>
4.112 + * <tr><td valign="top" headers="matches"><tt>\t</tt></td>
4.113 + * <td headers="matches">The tab character (<tt>'\u0009'</tt>)</td></tr>
4.114 + * <tr><td valign="top" headers="construct characters"><tt>\n</tt></td>
4.115 + * <td headers="matches">The newline (line feed) character (<tt>'\u000A'</tt>)</td></tr>
4.116 + * <tr><td valign="top" headers="construct characters"><tt>\r</tt></td>
4.117 + * <td headers="matches">The carriage-return character (<tt>'\u000D'</tt>)</td></tr>
4.118 + * <tr><td valign="top" headers="construct characters"><tt>\f</tt></td>
4.119 + * <td headers="matches">The form-feed character (<tt>'\u000C'</tt>)</td></tr>
4.120 + * <tr><td valign="top" headers="construct characters"><tt>\a</tt></td>
4.121 + * <td headers="matches">The alert (bell) character (<tt>'\u0007'</tt>)</td></tr>
4.122 + * <tr><td valign="top" headers="construct characters"><tt>\e</tt></td>
4.123 + * <td headers="matches">The escape character (<tt>'\u001B'</tt>)</td></tr>
4.124 + * <tr><td valign="top" headers="construct characters"><tt>\c</tt><i>x</i></td>
4.125 + * <td headers="matches">The control character corresponding to <i>x</i></td></tr>
4.126 + *
4.127 + * <tr><th> </th></tr>
4.128 + * <tr align="left"><th colspan="2" id="classes">Character classes</th></tr>
4.129 + *
4.130 + * <tr><td valign="top" headers="construct classes"><tt>[abc]</tt></td>
4.131 + * <td headers="matches"><tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (simple class)</td></tr>
4.132 + * <tr><td valign="top" headers="construct classes"><tt>[^abc]</tt></td>
4.133 + * <td headers="matches">Any character except <tt>a</tt>, <tt>b</tt>, or <tt>c</tt> (negation)</td></tr>
4.134 + * <tr><td valign="top" headers="construct classes"><tt>[a-zA-Z]</tt></td>
4.135 + * <td headers="matches"><tt>a</tt> through <tt>z</tt>
4.136 + * or <tt>A</tt> through <tt>Z</tt>, inclusive (range)</td></tr>
4.137 + * <tr><td valign="top" headers="construct classes"><tt>[a-d[m-p]]</tt></td>
4.138 + * <td headers="matches"><tt>a</tt> through <tt>d</tt>,
4.139 + * or <tt>m</tt> through <tt>p</tt>: <tt>[a-dm-p]</tt> (union)</td></tr>
4.140 + * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[def]]</tt></td>
4.141 + * <td headers="matches"><tt>d</tt>, <tt>e</tt>, or <tt>f</tt> (intersection)</tr>
4.142 + * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^bc]]</tt></td>
4.143 + * <td headers="matches"><tt>a</tt> through <tt>z</tt>,
4.144 + * except for <tt>b</tt> and <tt>c</tt>: <tt>[ad-z]</tt> (subtraction)</td></tr>
4.145 + * <tr><td valign="top" headers="construct classes"><tt>[a-z&&[^m-p]]</tt></td>
4.146 + * <td headers="matches"><tt>a</tt> through <tt>z</tt>,
4.147 + * and not <tt>m</tt> through <tt>p</tt>: <tt>[a-lq-z]</tt>(subtraction)</td></tr>
4.148 + * <tr><th> </th></tr>
4.149 + *
4.150 + * <tr align="left"><th colspan="2" id="predef">Predefined character classes</th></tr>
4.151 + *
4.152 + * <tr><td valign="top" headers="construct predef"><tt>.</tt></td>
4.153 + * <td headers="matches">Any character (may or may not match <a href="#lt">line terminators</a>)</td></tr>
4.154 + * <tr><td valign="top" headers="construct predef"><tt>\d</tt></td>
4.155 + * <td headers="matches">A digit: <tt>[0-9]</tt></td></tr>
4.156 + * <tr><td valign="top" headers="construct predef"><tt>\D</tt></td>
4.157 + * <td headers="matches">A non-digit: <tt>[^0-9]</tt></td></tr>
4.158 + * <tr><td valign="top" headers="construct predef"><tt>\s</tt></td>
4.159 + * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
4.160 + * <tr><td valign="top" headers="construct predef"><tt>\S</tt></td>
4.161 + * <td headers="matches">A non-whitespace character: <tt>[^\s]</tt></td></tr>
4.162 + * <tr><td valign="top" headers="construct predef"><tt>\w</tt></td>
4.163 + * <td headers="matches">A word character: <tt>[a-zA-Z_0-9]</tt></td></tr>
4.164 + * <tr><td valign="top" headers="construct predef"><tt>\W</tt></td>
4.165 + * <td headers="matches">A non-word character: <tt>[^\w]</tt></td></tr>
4.166 + *
4.167 + * <tr><th> </th></tr>
4.168 + * <tr align="left"><th colspan="2" id="posix">POSIX character classes</b> (US-ASCII only)<b></th></tr>
4.169 + *
4.170 + * <tr><td valign="top" headers="construct posix"><tt>\p{Lower}</tt></td>
4.171 + * <td headers="matches">A lower-case alphabetic character: <tt>[a-z]</tt></td></tr>
4.172 + * <tr><td valign="top" headers="construct posix"><tt>\p{Upper}</tt></td>
4.173 + * <td headers="matches">An upper-case alphabetic character:<tt>[A-Z]</tt></td></tr>
4.174 + * <tr><td valign="top" headers="construct posix"><tt>\p{ASCII}</tt></td>
4.175 + * <td headers="matches">All ASCII:<tt>[\x00-\x7F]</tt></td></tr>
4.176 + * <tr><td valign="top" headers="construct posix"><tt>\p{Alpha}</tt></td>
4.177 + * <td headers="matches">An alphabetic character:<tt>[\p{Lower}\p{Upper}]</tt></td></tr>
4.178 + * <tr><td valign="top" headers="construct posix"><tt>\p{Digit}</tt></td>
4.179 + * <td headers="matches">A decimal digit: <tt>[0-9]</tt></td></tr>
4.180 + * <tr><td valign="top" headers="construct posix"><tt>\p{Alnum}</tt></td>
4.181 + * <td headers="matches">An alphanumeric character:<tt>[\p{Alpha}\p{Digit}]</tt></td></tr>
4.182 + * <tr><td valign="top" headers="construct posix"><tt>\p{Punct}</tt></td>
4.183 + * <td headers="matches">Punctuation: One of <tt>!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~</tt></td></tr>
4.184 + * <!-- <tt>[\!"#\$%&'\(\)\*\+,\-\./:;\<=\>\?@\[\\\]\^_`\{\|\}~]</tt>
4.185 + * <tt>[\X21-\X2F\X31-\X40\X5B-\X60\X7B-\X7E]</tt> -->
4.186 + * <tr><td valign="top" headers="construct posix"><tt>\p{Graph}</tt></td>
4.187 + * <td headers="matches">A visible character: <tt>[\p{Alnum}\p{Punct}]</tt></td></tr>
4.188 + * <tr><td valign="top" headers="construct posix"><tt>\p{Print}</tt></td>
4.189 + * <td headers="matches">A printable character: <tt>[\p{Graph}\x20]</tt></td></tr>
4.190 + * <tr><td valign="top" headers="construct posix"><tt>\p{Blank}</tt></td>
4.191 + * <td headers="matches">A space or a tab: <tt>[ \t]</tt></td></tr>
4.192 + * <tr><td valign="top" headers="construct posix"><tt>\p{Cntrl}</tt></td>
4.193 + * <td headers="matches">A control character: <tt>[\x00-\x1F\x7F]</tt></td></tr>
4.194 + * <tr><td valign="top" headers="construct posix"><tt>\p{XDigit}</tt></td>
4.195 + * <td headers="matches">A hexadecimal digit: <tt>[0-9a-fA-F]</tt></td></tr>
4.196 + * <tr><td valign="top" headers="construct posix"><tt>\p{Space}</tt></td>
4.197 + * <td headers="matches">A whitespace character: <tt>[ \t\n\x0B\f\r]</tt></td></tr>
4.198 + *
4.199 + * <tr><th> </th></tr>
4.200 + * <tr align="left"><th colspan="2">java.lang.Character classes (simple <a href="#jcc">java character type</a>)</th></tr>
4.201 + *
4.202 + * <tr><td valign="top"><tt>\p{javaLowerCase}</tt></td>
4.203 + * <td>Equivalent to java.lang.Character.isLowerCase()</td></tr>
4.204 + * <tr><td valign="top"><tt>\p{javaUpperCase}</tt></td>
4.205 + * <td>Equivalent to java.lang.Character.isUpperCase()</td></tr>
4.206 + * <tr><td valign="top"><tt>\p{javaWhitespace}</tt></td>
4.207 + * <td>Equivalent to java.lang.Character.isWhitespace()</td></tr>
4.208 + * <tr><td valign="top"><tt>\p{javaMirrored}</tt></td>
4.209 + * <td>Equivalent to java.lang.Character.isMirrored()</td></tr>
4.210 + *
4.211 + * <tr><th> </th></tr>
4.212 + * <tr align="left"><th colspan="2" id="unicode">Classes for Unicode scripts, blocks, categories and binary properties</th></tr>
4.213 + * * <tr><td valign="top" headers="construct unicode"><tt>\p{IsLatin}</tt></td>
4.214 + * <td headers="matches">A Latin script character (<a href="#usc">script</a>)</td></tr>
4.215 + * <tr><td valign="top" headers="construct unicode"><tt>\p{InGreek}</tt></td>
4.216 + * <td headers="matches">A character in the Greek block (<a href="#ubc">block</a>)</td></tr>
4.217 + * <tr><td valign="top" headers="construct unicode"><tt>\p{Lu}</tt></td>
4.218 + * <td headers="matches">An uppercase letter (<a href="#ucc">category</a>)</td></tr>
4.219 + * <tr><td valign="top" headers="construct unicode"><tt>\p{IsAlphabetic}</tt></td>
4.220 + * <td headers="matches">An alphabetic character (<a href="#ubpc">binary property</a>)</td></tr>
4.221 + * <tr><td valign="top" headers="construct unicode"><tt>\p{Sc}</tt></td>
4.222 + * <td headers="matches">A currency symbol</td></tr>
4.223 + * <tr><td valign="top" headers="construct unicode"><tt>\P{InGreek}</tt></td>
4.224 + * <td headers="matches">Any character except one in the Greek block (negation)</td></tr>
4.225 + * <tr><td valign="top" headers="construct unicode"><tt>[\p{L}&&[^\p{Lu}]] </tt></td>
4.226 + * <td headers="matches">Any letter except an uppercase letter (subtraction)</td></tr>
4.227 + *
4.228 + * <tr><th> </th></tr>
4.229 + * <tr align="left"><th colspan="2" id="bounds">Boundary matchers</th></tr>
4.230 + *
4.231 + * <tr><td valign="top" headers="construct bounds"><tt>^</tt></td>
4.232 + * <td headers="matches">The beginning of a line</td></tr>
4.233 + * <tr><td valign="top" headers="construct bounds"><tt>$</tt></td>
4.234 + * <td headers="matches">The end of a line</td></tr>
4.235 + * <tr><td valign="top" headers="construct bounds"><tt>\b</tt></td>
4.236 + * <td headers="matches">A word boundary</td></tr>
4.237 + * <tr><td valign="top" headers="construct bounds"><tt>\B</tt></td>
4.238 + * <td headers="matches">A non-word boundary</td></tr>
4.239 + * <tr><td valign="top" headers="construct bounds"><tt>\A</tt></td>
4.240 + * <td headers="matches">The beginning of the input</td></tr>
4.241 + * <tr><td valign="top" headers="construct bounds"><tt>\G</tt></td>
4.242 + * <td headers="matches">The end of the previous match</td></tr>
4.243 + * <tr><td valign="top" headers="construct bounds"><tt>\Z</tt></td>
4.244 + * <td headers="matches">The end of the input but for the final
4.245 + * <a href="#lt">terminator</a>, if any</td></tr>
4.246 + * <tr><td valign="top" headers="construct bounds"><tt>\z</tt></td>
4.247 + * <td headers="matches">The end of the input</td></tr>
4.248 + *
4.249 + * <tr><th> </th></tr>
4.250 + * <tr align="left"><th colspan="2" id="greedy">Greedy quantifiers</th></tr>
4.251 + *
4.252 + * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>?</tt></td>
4.253 + * <td headers="matches"><i>X</i>, once or not at all</td></tr>
4.254 + * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>*</tt></td>
4.255 + * <td headers="matches"><i>X</i>, zero or more times</td></tr>
4.256 + * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>+</tt></td>
4.257 + * <td headers="matches"><i>X</i>, one or more times</td></tr>
4.258 + * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>}</tt></td>
4.259 + * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
4.260 + * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,}</tt></td>
4.261 + * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
4.262 + * <tr><td valign="top" headers="construct greedy"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}</tt></td>
4.263 + * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
4.264 + *
4.265 + * <tr><th> </th></tr>
4.266 + * <tr align="left"><th colspan="2" id="reluc">Reluctant quantifiers</th></tr>
4.267 + *
4.268 + * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>??</tt></td>
4.269 + * <td headers="matches"><i>X</i>, once or not at all</td></tr>
4.270 + * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>*?</tt></td>
4.271 + * <td headers="matches"><i>X</i>, zero or more times</td></tr>
4.272 + * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>+?</tt></td>
4.273 + * <td headers="matches"><i>X</i>, one or more times</td></tr>
4.274 + * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>}?</tt></td>
4.275 + * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
4.276 + * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,}?</tt></td>
4.277 + * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
4.278 + * <tr><td valign="top" headers="construct reluc"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}?</tt></td>
4.279 + * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
4.280 + *
4.281 + * <tr><th> </th></tr>
4.282 + * <tr align="left"><th colspan="2" id="poss">Possessive quantifiers</th></tr>
4.283 + *
4.284 + * <tr><td valign="top" headers="construct poss"><i>X</i><tt>?+</tt></td>
4.285 + * <td headers="matches"><i>X</i>, once or not at all</td></tr>
4.286 + * <tr><td valign="top" headers="construct poss"><i>X</i><tt>*+</tt></td>
4.287 + * <td headers="matches"><i>X</i>, zero or more times</td></tr>
4.288 + * <tr><td valign="top" headers="construct poss"><i>X</i><tt>++</tt></td>
4.289 + * <td headers="matches"><i>X</i>, one or more times</td></tr>
4.290 + * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>}+</tt></td>
4.291 + * <td headers="matches"><i>X</i>, exactly <i>n</i> times</td></tr>
4.292 + * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,}+</tt></td>
4.293 + * <td headers="matches"><i>X</i>, at least <i>n</i> times</td></tr>
4.294 + * <tr><td valign="top" headers="construct poss"><i>X</i><tt>{</tt><i>n</i><tt>,</tt><i>m</i><tt>}+</tt></td>
4.295 + * <td headers="matches"><i>X</i>, at least <i>n</i> but not more than <i>m</i> times</td></tr>
4.296 + *
4.297 + * <tr><th> </th></tr>
4.298 + * <tr align="left"><th colspan="2" id="logical">Logical operators</th></tr>
4.299 + *
4.300 + * <tr><td valign="top" headers="construct logical"><i>XY</i></td>
4.301 + * <td headers="matches"><i>X</i> followed by <i>Y</i></td></tr>
4.302 + * <tr><td valign="top" headers="construct logical"><i>X</i><tt>|</tt><i>Y</i></td>
4.303 + * <td headers="matches">Either <i>X</i> or <i>Y</i></td></tr>
4.304 + * <tr><td valign="top" headers="construct logical"><tt>(</tt><i>X</i><tt>)</tt></td>
4.305 + * <td headers="matches">X, as a <a href="#cg">capturing group</a></td></tr>
4.306 + *
4.307 + * <tr><th> </th></tr>
4.308 + * <tr align="left"><th colspan="2" id="backref">Back references</th></tr>
4.309 + *
4.310 + * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>n</i></td>
4.311 + * <td valign="bottom" headers="matches">Whatever the <i>n</i><sup>th</sup>
4.312 + * <a href="#cg">capturing group</a> matched</td></tr>
4.313 + *
4.314 + * <tr><td valign="bottom" headers="construct backref"><tt>\</tt><i>k</i><<i>name</i>></td>
4.315 + * <td valign="bottom" headers="matches">Whatever the
4.316 + * <a href="#groupname">named-capturing group</a> "name" matched</td></tr>
4.317 + *
4.318 + * <tr><th> </th></tr>
4.319 + * <tr align="left"><th colspan="2" id="quot">Quotation</th></tr>
4.320 + *
4.321 + * <tr><td valign="top" headers="construct quot"><tt>\</tt></td>
4.322 + * <td headers="matches">Nothing, but quotes the following character</td></tr>
4.323 + * <tr><td valign="top" headers="construct quot"><tt>\Q</tt></td>
4.324 + * <td headers="matches">Nothing, but quotes all characters until <tt>\E</tt></td></tr>
4.325 + * <tr><td valign="top" headers="construct quot"><tt>\E</tt></td>
4.326 + * <td headers="matches">Nothing, but ends quoting started by <tt>\Q</tt></td></tr>
4.327 + * <!-- Metachars: !$()*+.<>?[\]^{|} -->
4.328 + *
4.329 + * <tr><th> </th></tr>
4.330 + * <tr align="left"><th colspan="2" id="special">Special constructs (named-capturing and non-capturing)</th></tr>
4.331 + *
4.332 + * <tr><td valign="top" headers="construct special"><tt>(?<<a href="#groupname">name</a>></tt><i>X</i><tt>)</tt></td>
4.333 + * <td headers="matches"><i>X</i>, as a named-capturing group</td></tr>
4.334 + * <tr><td valign="top" headers="construct special"><tt>(?:</tt><i>X</i><tt>)</tt></td>
4.335 + * <td headers="matches"><i>X</i>, as a non-capturing group</td></tr>
4.336 + * <tr><td valign="top" headers="construct special"><tt>(?idmsuxU-idmsuxU) </tt></td>
4.337 + * <td headers="matches">Nothing, but turns match flags <a href="#CASE_INSENSITIVE">i</a>
4.338 + * <a href="#UNIX_LINES">d</a> <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a>
4.339 + * <a href="#UNICODE_CASE">u</a> <a href="#COMMENTS">x</a> <a href="#UNICODE_CHARACTER_CLASS">U</a>
4.340 + * on - off</td></tr>
4.341 + * <tr><td valign="top" headers="construct special"><tt>(?idmsux-idmsux:</tt><i>X</i><tt>)</tt> </td>
4.342 + * <td headers="matches"><i>X</i>, as a <a href="#cg">non-capturing group</a> with the
4.343 + * given flags <a href="#CASE_INSENSITIVE">i</a> <a href="#UNIX_LINES">d</a>
4.344 + * <a href="#MULTILINE">m</a> <a href="#DOTALL">s</a> <a href="#UNICODE_CASE">u</a >
4.345 + * <a href="#COMMENTS">x</a> on - off</td></tr>
4.346 + * <tr><td valign="top" headers="construct special"><tt>(?=</tt><i>X</i><tt>)</tt></td>
4.347 + * <td headers="matches"><i>X</i>, via zero-width positive lookahead</td></tr>
4.348 + * <tr><td valign="top" headers="construct special"><tt>(?!</tt><i>X</i><tt>)</tt></td>
4.349 + * <td headers="matches"><i>X</i>, via zero-width negative lookahead</td></tr>
4.350 + * <tr><td valign="top" headers="construct special"><tt>(?<=</tt><i>X</i><tt>)</tt></td>
4.351 + * <td headers="matches"><i>X</i>, via zero-width positive lookbehind</td></tr>
4.352 + * <tr><td valign="top" headers="construct special"><tt>(?<!</tt><i>X</i><tt>)</tt></td>
4.353 + * <td headers="matches"><i>X</i>, via zero-width negative lookbehind</td></tr>
4.354 + * <tr><td valign="top" headers="construct special"><tt>(?></tt><i>X</i><tt>)</tt></td>
4.355 + * <td headers="matches"><i>X</i>, as an independent, non-capturing group</td></tr>
4.356 + *
4.357 + * </table>
4.358 + *
4.359 + * <hr>
4.360 + *
4.361 + *
4.362 + * <a name="bs">
4.363 + * <h4> Backslashes, escapes, and quoting </h4>
4.364 + *
4.365 + * <p> The backslash character (<tt>'\'</tt>) serves to introduce escaped
4.366 + * constructs, as defined in the table above, as well as to quote characters
4.367 + * that otherwise would be interpreted as unescaped constructs. Thus the
4.368 + * expression <tt>\\</tt> matches a single backslash and <tt>\{</tt> matches a
4.369 + * left brace.
4.370 + *
4.371 + * <p> It is an error to use a backslash prior to any alphabetic character that
4.372 + * does not denote an escaped construct; these are reserved for future
4.373 + * extensions to the regular-expression language. A backslash may be used
4.374 + * prior to a non-alphabetic character regardless of whether that character is
4.375 + * part of an unescaped construct.
4.376 + *
4.377 + * <p> Backslashes within string literals in Java source code are interpreted
4.378 + * as required by
4.379 + * <cite>The Java™ Language Specification</cite>
4.380 + * as either Unicode escapes (section 3.3) or other character escapes (section 3.10.6)
4.381 + * It is therefore necessary to double backslashes in string
4.382 + * literals that represent regular expressions to protect them from
4.383 + * interpretation by the Java bytecode compiler. The string literal
4.384 + * <tt>"\b"</tt>, for example, matches a single backspace character when
4.385 + * interpreted as a regular expression, while <tt>"\\b"</tt> matches a
4.386 + * word boundary. The string literal <tt>"\(hello\)"</tt> is illegal
4.387 + * and leads to a compile-time error; in order to match the string
4.388 + * <tt>(hello)</tt> the string literal <tt>"\\(hello\\)"</tt>
4.389 + * must be used.
4.390 + *
4.391 + * <a name="cc">
4.392 + * <h4> Character Classes </h4>
4.393 + *
4.394 + * <p> Character classes may appear within other character classes, and
4.395 + * may be composed by the union operator (implicit) and the intersection
4.396 + * operator (<tt>&&</tt>).
4.397 + * The union operator denotes a class that contains every character that is
4.398 + * in at least one of its operand classes. The intersection operator
4.399 + * denotes a class that contains every character that is in both of its
4.400 + * operand classes.
4.401 + *
4.402 + * <p> The precedence of character-class operators is as follows, from
4.403 + * highest to lowest:
4.404 + *
4.405 + * <blockquote><table border="0" cellpadding="1" cellspacing="0"
4.406 + * summary="Precedence of character class operators.">
4.407 + * <tr><th>1 </th>
4.408 + * <td>Literal escape </td>
4.409 + * <td><tt>\x</tt></td></tr>
4.410 + * <tr><th>2 </th>
4.411 + * <td>Grouping</td>
4.412 + * <td><tt>[...]</tt></td></tr>
4.413 + * <tr><th>3 </th>
4.414 + * <td>Range</td>
4.415 + * <td><tt>a-z</tt></td></tr>
4.416 + * <tr><th>4 </th>
4.417 + * <td>Union</td>
4.418 + * <td><tt>[a-e][i-u]</tt></td></tr>
4.419 + * <tr><th>5 </th>
4.420 + * <td>Intersection</td>
4.421 + * <td><tt>[a-z&&[aeiou]]</tt></td></tr>
4.422 + * </table></blockquote>
4.423 + *
4.424 + * <p> Note that a different set of metacharacters are in effect inside
4.425 + * a character class than outside a character class. For instance, the
4.426 + * regular expression <tt>.</tt> loses its special meaning inside a
4.427 + * character class, while the expression <tt>-</tt> becomes a range
4.428 + * forming metacharacter.
4.429 + *
4.430 + * <a name="lt">
4.431 + * <h4> Line terminators </h4>
4.432 + *
4.433 + * <p> A <i>line terminator</i> is a one- or two-character sequence that marks
4.434 + * the end of a line of the input character sequence. The following are
4.435 + * recognized as line terminators:
4.436 + *
4.437 + * <ul>
4.438 + *
4.439 + * <li> A newline (line feed) character (<tt>'\n'</tt>),
4.440 + *
4.441 + * <li> A carriage-return character followed immediately by a newline
4.442 + * character (<tt>"\r\n"</tt>),
4.443 + *
4.444 + * <li> A standalone carriage-return character (<tt>'\r'</tt>),
4.445 + *
4.446 + * <li> A next-line character (<tt>'\u0085'</tt>),
4.447 + *
4.448 + * <li> A line-separator character (<tt>'\u2028'</tt>), or
4.449 + *
4.450 + * <li> A paragraph-separator character (<tt>'\u2029</tt>).
4.451 + *
4.452 + * </ul>
4.453 + * <p>If {@link #UNIX_LINES} mode is activated, then the only line terminators
4.454 + * recognized are newline characters.
4.455 + *
4.456 + * <p> The regular expression <tt>.</tt> matches any character except a line
4.457 + * terminator unless the {@link #DOTALL} flag is specified.
4.458 + *
4.459 + * <p> By default, the regular expressions <tt>^</tt> and <tt>$</tt> ignore
4.460 + * line terminators and only match at the beginning and the end, respectively,
4.461 + * of the entire input sequence. If {@link #MULTILINE} mode is activated then
4.462 + * <tt>^</tt> matches at the beginning of input and after any line terminator
4.463 + * except at the end of input. When in {@link #MULTILINE} mode <tt>$</tt>
4.464 + * matches just before a line terminator or the end of the input sequence.
4.465 + *
4.466 + * <a name="cg">
4.467 + * <h4> Groups and capturing </h4>
4.468 + *
4.469 + * <a name="gnumber">
4.470 + * <h5> Group number </h5>
4.471 + * <p> Capturing groups are numbered by counting their opening parentheses from
4.472 + * left to right. In the expression <tt>((A)(B(C)))</tt>, for example, there
4.473 + * are four such groups: </p>
4.474 + *
4.475 + * <blockquote><table cellpadding=1 cellspacing=0 summary="Capturing group numberings">
4.476 + * <tr><th>1 </th>
4.477 + * <td><tt>((A)(B(C)))</tt></td></tr>
4.478 + * <tr><th>2 </th>
4.479 + * <td><tt>(A)</tt></td></tr>
4.480 + * <tr><th>3 </th>
4.481 + * <td><tt>(B(C))</tt></td></tr>
4.482 + * <tr><th>4 </th>
4.483 + * <td><tt>(C)</tt></td></tr>
4.484 + * </table></blockquote>
4.485 + *
4.486 + * <p> Group zero always stands for the entire expression.
4.487 + *
4.488 + * <p> Capturing groups are so named because, during a match, each subsequence
4.489 + * of the input sequence that matches such a group is saved. The captured
4.490 + * subsequence may be used later in the expression, via a back reference, and
4.491 + * may also be retrieved from the matcher once the match operation is complete.
4.492 + *
4.493 + * <a name="groupname">
4.494 + * <h5> Group name </h5>
4.495 + * <p>A capturing group can also be assigned a "name", a <tt>named-capturing group</tt>,
4.496 + * and then be back-referenced later by the "name". Group names are composed of
4.497 + * the following characters. The first character must be a <tt>letter</tt>.
4.498 + *
4.499 + * <ul>
4.500 + * <li> The uppercase letters <tt>'A'</tt> through <tt>'Z'</tt>
4.501 + * (<tt>'\u0041'</tt> through <tt>'\u005a'</tt>),
4.502 + * <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt>
4.503 + * (<tt>'\u0061'</tt> through <tt>'\u007a'</tt>),
4.504 + * <li> The digits <tt>'0'</tt> through <tt>'9'</tt>
4.505 + * (<tt>'\u0030'</tt> through <tt>'\u0039'</tt>),
4.506 + * </ul>
4.507 + *
4.508 + * <p> A <tt>named-capturing group</tt> is still numbered as described in
4.509 + * <a href="#gnumber">Group number</a>.
4.510 + *
4.511 + * <p> The captured input associated with a group is always the subsequence
4.512 + * that the group most recently matched. If a group is evaluated a second time
4.513 + * because of quantification then its previously-captured value, if any, will
4.514 + * be retained if the second evaluation fails. Matching the string
4.515 + * <tt>"aba"</tt> against the expression <tt>(a(b)?)+</tt>, for example, leaves
4.516 + * group two set to <tt>"b"</tt>. All captured input is discarded at the
4.517 + * beginning of each match.
4.518 + *
4.519 + * <p> Groups beginning with <tt>(?</tt> are either pure, <i>non-capturing</i> groups
4.520 + * that do not capture text and do not count towards the group total, or
4.521 + * <i>named-capturing</i> group.
4.522 + *
4.523 + * <h4> Unicode support </h4>
4.524 + *
4.525 + * <p> This class is in conformance with Level 1 of <a
4.526 + * href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
4.527 + * Standard #18: Unicode Regular Expression</i></a>, plus RL2.1
4.528 + * Canonical Equivalents.
4.529 + * <p>
4.530 + * <b>Unicode escape sequences</b> such as <tt>\u2014</tt> in Java source code
4.531 + * are processed as described in section 3.3 of
4.532 + * <cite>The Java™ Language Specification</cite>.
4.533 + * Such escape sequences are also implemented directly by the regular-expression
4.534 + * parser so that Unicode escapes can be used in expressions that are read from
4.535 + * files or from the keyboard. Thus the strings <tt>"\u2014"</tt> and
4.536 + * <tt>"\\u2014"</tt>, while not equal, compile into the same pattern, which
4.537 + * matches the character with hexadecimal value <tt>0x2014</tt>.
4.538 + * <p>
4.539 + * A Unicode character can also be represented in a regular-expression by
4.540 + * using its <b>Hex notation</b>(hexadecimal code point value) directly as described in construct
4.541 + * <tt>\x{...}</tt>, for example a supplementary character U+2011F
4.542 + * can be specified as <tt>\x{2011F}</tt>, instead of two consecutive
4.543 + * Unicode escape sequences of the surrogate pair
4.544 + * <tt>\uD840</tt><tt>\uDD1F</tt>.
4.545 + * <p>
4.546 + * Unicode scripts, blocks, categories and binary properties are written with
4.547 + * the <tt>\p</tt> and <tt>\P</tt> constructs as in Perl.
4.548 + * <tt>\p{</tt><i>prop</i><tt>}</tt> matches if
4.549 + * the input has the property <i>prop</i>, while <tt>\P{</tt><i>prop</i><tt>}</tt>
4.550 + * does not match if the input has that property.
4.551 + * <p>
4.552 + * Scripts, blocks, categories and binary properties can be used both inside
4.553 + * and outside of a character class.
4.554 + * <a name="usc">
4.555 + * <p>
4.556 + * <b>Scripts</b> are specified either with the prefix {@code Is}, as in
4.557 + * {@code IsHiragana}, or by using the {@code script} keyword (or its short
4.558 + * form {@code sc})as in {@code script=Hiragana} or {@code sc=Hiragana}.
4.559 + * <p>
4.560 + * The script names supported by <code>Pattern</code> are the valid script names
4.561 + * accepted and defined by
4.562 + * {@link java.lang.Character.UnicodeScript#forName(String) UnicodeScript.forName}.
4.563 + * <a name="ubc">
4.564 + * <p>
4.565 + * <b>Blocks</b> are specified with the prefix {@code In}, as in
4.566 + * {@code InMongolian}, or by using the keyword {@code block} (or its short
4.567 + * form {@code blk}) as in {@code block=Mongolian} or {@code blk=Mongolian}.
4.568 + * <p>
4.569 + * The block names supported by <code>Pattern</code> are the valid block names
4.570 + * accepted and defined by
4.571 + * {@link java.lang.Character.UnicodeBlock#forName(String) UnicodeBlock.forName}.
4.572 + * <p>
4.573 + * <a name="ucc">
4.574 + * <b>Categories</b> may be specified with the optional prefix {@code Is}:
4.575 + * Both {@code \p{L}} and {@code \p{IsL}} denote the category of Unicode
4.576 + * letters. Same as scripts and blocks, categories can also be specified
4.577 + * by using the keyword {@code general_category} (or its short form
4.578 + * {@code gc}) as in {@code general_category=Lu} or {@code gc=Lu}.
4.579 + * <p>
4.580 + * The supported categories are those of
4.581 + * <a href="http://www.unicode.org/unicode/standard/standard.html">
4.582 + * <i>The Unicode Standard</i></a> in the version specified by the
4.583 + * {@link java.lang.Character Character} class. The category names are those
4.584 + * defined in the Standard, both normative and informative.
4.585 + * <p>
4.586 + * <a name="ubpc">
4.587 + * <b>Binary properties</b> are specified with the prefix {@code Is}, as in
4.588 + * {@code IsAlphabetic}. The supported binary properties by <code>Pattern</code>
4.589 + * are
4.590 + * <ul>
4.591 + * <li> Alphabetic
4.592 + * <li> Ideographic
4.593 + * <li> Letter
4.594 + * <li> Lowercase
4.595 + * <li> Uppercase
4.596 + * <li> Titlecase
4.597 + * <li> Punctuation
4.598 + * <Li> Control
4.599 + * <li> White_Space
4.600 + * <li> Digit
4.601 + * <li> Hex_Digit
4.602 + * <li> Noncharacter_Code_Point
4.603 + * <li> Assigned
4.604 + * </ul>
4.605 +
4.606 +
4.607 + * <p>
4.608 + * <b>Predefined Character classes</b> and <b>POSIX character classes</b> are in
4.609 + * conformance with the recommendation of <i>Annex C: Compatibility Properties</i>
4.610 + * of <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Regular Expression
4.611 + * </i></a>, when {@link #UNICODE_CHARACTER_CLASS} flag is specified.
4.612 + * <p>
4.613 + * <table border="0" cellpadding="1" cellspacing="0"
4.614 + * summary="predefined and posix character classes in Unicode mode">
4.615 + * <tr align="left">
4.616 + * <th bgcolor="#CCCCFF" align="left" id="classes">Classes</th>
4.617 + * <th bgcolor="#CCCCFF" align="left" id="matches">Matches</th>
4.618 + *</tr>
4.619 + * <tr><td><tt>\p{Lower}</tt></td>
4.620 + * <td>A lowercase character:<tt>\p{IsLowercase}</tt></td></tr>
4.621 + * <tr><td><tt>\p{Upper}</tt></td>
4.622 + * <td>An uppercase character:<tt>\p{IsUppercase}</tt></td></tr>
4.623 + * <tr><td><tt>\p{ASCII}</tt></td>
4.624 + * <td>All ASCII:<tt>[\x00-\x7F]</tt></td></tr>
4.625 + * <tr><td><tt>\p{Alpha}</tt></td>
4.626 + * <td>An alphabetic character:<tt>\p{IsAlphabetic}</tt></td></tr>
4.627 + * <tr><td><tt>\p{Digit}</tt></td>
4.628 + * <td>A decimal digit character:<tt>p{IsDigit}</tt></td></tr>
4.629 + * <tr><td><tt>\p{Alnum}</tt></td>
4.630 + * <td>An alphanumeric character:<tt>[\p{IsAlphabetic}\p{IsDigit}]</tt></td></tr>
4.631 + * <tr><td><tt>\p{Punct}</tt></td>
4.632 + * <td>A punctuation character:<tt>p{IsPunctuation}</tt></td></tr>
4.633 + * <tr><td><tt>\p{Graph}</tt></td>
4.634 + * <td>A visible character: <tt>[^\p{IsWhite_Space}\p{gc=Cc}\p{gc=Cs}\p{gc=Cn}]</tt></td></tr>
4.635 + * <tr><td><tt>\p{Print}</tt></td>
4.636 + * <td>A printable character: <tt>[\p{Graph}\p{Blank}&&[^\p{Cntrl}]]</tt></td></tr>
4.637 + * <tr><td><tt>\p{Blank}</tt></td>
4.638 + * <td>A space or a tab: <tt>[\p{IsWhite_Space}&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]]</tt></td></tr>
4.639 + * <tr><td><tt>\p{Cntrl}</tt></td>
4.640 + * <td>A control character: <tt>\p{gc=Cc}</tt></td></tr>
4.641 + * <tr><td><tt>\p{XDigit}</tt></td>
4.642 + * <td>A hexadecimal digit: <tt>[\p{gc=Nd}\p{IsHex_Digit}]</tt></td></tr>
4.643 + * <tr><td><tt>\p{Space}</tt></td>
4.644 + * <td>A whitespace character:<tt>\p{IsWhite_Space}</tt></td></tr>
4.645 + * <tr><td><tt>\d</tt></td>
4.646 + * <td>A digit: <tt>\p{IsDigit}</tt></td></tr>
4.647 + * <tr><td><tt>\D</tt></td>
4.648 + * <td>A non-digit: <tt>[^\d]</tt></td></tr>
4.649 + * <tr><td><tt>\s</tt></td>
4.650 + * <td>A whitespace character: <tt>\p{IsWhite_Space}</tt></td></tr>
4.651 + * <tr><td><tt>\S</tt></td>
4.652 + * <td>A non-whitespace character: <tt>[^\s]</tt></td></tr>
4.653 + * <tr><td><tt>\w</tt></td>
4.654 + * <td>A word character: <tt>[\p{Alpha}\p{gc=Mn}\p{gc=Me}\p{gc=Mc}\p{Digit}\p{gc=Pc}]</tt></td></tr>
4.655 + * <tr><td><tt>\W</tt></td>
4.656 + * <td>A non-word character: <tt>[^\w]</tt></td></tr>
4.657 + * </table>
4.658 + * <p>
4.659 + * <a name="jcc">
4.660 + * Categories that behave like the java.lang.Character
4.661 + * boolean is<i>methodname</i> methods (except for the deprecated ones) are
4.662 + * available through the same <tt>\p{</tt><i>prop</i><tt>}</tt> syntax where
4.663 + * the specified property has the name <tt>java<i>methodname</i></tt>.
4.664 + *
4.665 + * <h4> Comparison to Perl 5 </h4>
4.666 + *
4.667 + * <p>The <code>Pattern</code> engine performs traditional NFA-based matching
4.668 + * with ordered alternation as occurs in Perl 5.
4.669 + *
4.670 + * <p> Perl constructs not supported by this class: </p>
4.671 + *
4.672 + * <ul>
4.673 + * <li><p> Predefined character classes (Unicode character)
4.674 + * <p><tt>\h </tt>A horizontal whitespace
4.675 + * <p><tt>\H </tt>A non horizontal whitespace
4.676 + * <p><tt>\v </tt>A vertical whitespace
4.677 + * <p><tt>\V </tt>A non vertical whitespace
4.678 + * <p><tt>\R </tt>Any Unicode linebreak sequence
4.679 + * <tt>\u005cu000D\u005cu000A|[\u005cu000A\u005cu000B\u005cu000C\u005cu000D\u005cu0085\u005cu2028\u005cu2029]</tt>
4.680 + * <p><tt>\X </tt>Match Unicode
4.681 + * <a href="http://www.unicode.org/reports/tr18/#Default_Grapheme_Clusters">
4.682 + * <i>extended grapheme cluster</i></a>
4.683 + * </p></li>
4.684 + *
4.685 + * <li><p> The backreference constructs, <tt>\g{</tt><i>n</i><tt>}</tt> for
4.686 + * the <i>n</i><sup>th</sup><a href="#cg">capturing group</a> and
4.687 + * <tt>\g{</tt><i>name</i><tt>}</tt> for
4.688 + * <a href="#groupname">named-capturing group</a>.
4.689 + * </p></li>
4.690 + *
4.691 + * <li><p> The named character construct, <tt>\N{</tt><i>name</i><tt>}</tt>
4.692 + * for a Unicode character by its name.
4.693 + * </p></li>
4.694 + *
4.695 + * <li><p> The conditional constructs
4.696 + * <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>)</tt> and
4.697 + * <tt>(?(</tt><i>condition</i><tt>)</tt><i>X</i><tt>|</tt><i>Y</i><tt>)</tt>,
4.698 + * </p></li>
4.699 + *
4.700 + * <li><p> The embedded code constructs <tt>(?{</tt><i>code</i><tt>})</tt>
4.701 + * and <tt>(??{</tt><i>code</i><tt>})</tt>,</p></li>
4.702 + *
4.703 + * <li><p> The embedded comment syntax <tt>(?#comment)</tt>, and </p></li>
4.704 + *
4.705 + * <li><p> The preprocessing operations <tt>\l</tt> <tt>\u</tt>,
4.706 + * <tt>\L</tt>, and <tt>\U</tt>. </p></li>
4.707 + *
4.708 + * </ul>
4.709 + *
4.710 + * <p> Constructs supported by this class but not by Perl: </p>
4.711 + *
4.712 + * <ul>
4.713 + *
4.714 + * <li><p> Character-class union and intersection as described
4.715 + * <a href="#cc">above</a>.</p></li>
4.716 + *
4.717 + * </ul>
4.718 + *
4.719 + * <p> Notable differences from Perl: </p>
4.720 + *
4.721 + * <ul>
4.722 + *
4.723 + * <li><p> In Perl, <tt>\1</tt> through <tt>\9</tt> are always interpreted
4.724 + * as back references; a backslash-escaped number greater than <tt>9</tt> is
4.725 + * treated as a back reference if at least that many subexpressions exist,
4.726 + * otherwise it is interpreted, if possible, as an octal escape. In this
4.727 + * class octal escapes must always begin with a zero. In this class,
4.728 + * <tt>\1</tt> through <tt>\9</tt> are always interpreted as back
4.729 + * references, and a larger number is accepted as a back reference if at
4.730 + * least that many subexpressions exist at that point in the regular
4.731 + * expression, otherwise the parser will drop digits until the number is
4.732 + * smaller or equal to the existing number of groups or it is one digit.
4.733 + * </p></li>
4.734 + *
4.735 + * <li><p> Perl uses the <tt>g</tt> flag to request a match that resumes
4.736 + * where the last match left off. This functionality is provided implicitly
4.737 + * by the {@link Matcher} class: Repeated invocations of the {@link
4.738 + * Matcher#find find} method will resume where the last match left off,
4.739 + * unless the matcher is reset. </p></li>
4.740 + *
4.741 + * <li><p> In Perl, embedded flags at the top level of an expression affect
4.742 + * the whole expression. In this class, embedded flags always take effect
4.743 + * at the point at which they appear, whether they are at the top level or
4.744 + * within a group; in the latter case, flags are restored at the end of the
4.745 + * group just as in Perl. </p></li>
4.746 + *
4.747 + * </ul>
4.748 + *
4.749 + *
4.750 + * <p> For a more precise description of the behavior of regular expression
4.751 + * constructs, please see <a href="http://www.oreilly.com/catalog/regex3/">
4.752 + * <i>Mastering Regular Expressions, 3nd Edition</i>, Jeffrey E. F. Friedl,
4.753 + * O'Reilly and Associates, 2006.</a>
4.754 + * </p>
4.755 + *
4.756 + * @see java.lang.String#split(String, int)
4.757 + * @see java.lang.String#split(String)
4.758 + *
4.759 + * @author Mike McCloskey
4.760 + * @author Mark Reinhold
4.761 + * @author JSR-51 Expert Group
4.762 + * @since 1.4
4.763 + * @spec JSR-51
4.764 + */
4.765 +
4.766 +public final class Pattern
4.767 + implements java.io.Serializable
4.768 +{
4.769 +
4.770 + /**
4.771 + * Regular expression modifier values. Instead of being passed as
4.772 + * arguments, they can also be passed as inline modifiers.
4.773 + * For example, the following statements have the same effect.
4.774 + * <pre>
4.775 + * RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M);
4.776 + * RegExp r2 = RegExp.compile("(?im)abc", 0);
4.777 + * </pre>
4.778 + *
4.779 + * The flags are duplicated so that the familiar Perl match flag
4.780 + * names are available.
4.781 + */
4.782 +
4.783 + /**
4.784 + * Enables Unix lines mode.
4.785 + *
4.786 + * <p> In this mode, only the <tt>'\n'</tt> line terminator is recognized
4.787 + * in the behavior of <tt>.</tt>, <tt>^</tt>, and <tt>$</tt>.
4.788 + *
4.789 + * <p> Unix lines mode can also be enabled via the embedded flag
4.790 + * expression <tt>(?d)</tt>.
4.791 + */
4.792 + public static final int UNIX_LINES = 0x01;
4.793 +
4.794 + /**
4.795 + * Enables case-insensitive matching.
4.796 + *
4.797 + * <p> By default, case-insensitive matching assumes that only characters
4.798 + * in the US-ASCII charset are being matched. Unicode-aware
4.799 + * case-insensitive matching can be enabled by specifying the {@link
4.800 + * #UNICODE_CASE} flag in conjunction with this flag.
4.801 + *
4.802 + * <p> Case-insensitive matching can also be enabled via the embedded flag
4.803 + * expression <tt>(?i)</tt>.
4.804 + *
4.805 + * <p> Specifying this flag may impose a slight performance penalty. </p>
4.806 + */
4.807 + public static final int CASE_INSENSITIVE = 0x02;
4.808 +
4.809 + /**
4.810 + * Permits whitespace and comments in pattern.
4.811 + *
4.812 + * <p> In this mode, whitespace is ignored, and embedded comments starting
4.813 + * with <tt>#</tt> are ignored until the end of a line.
4.814 + *
4.815 + * <p> Comments mode can also be enabled via the embedded flag
4.816 + * expression <tt>(?x)</tt>.
4.817 + */
4.818 + public static final int COMMENTS = 0x04;
4.819 +
4.820 + /**
4.821 + * Enables multiline mode.
4.822 + *
4.823 + * <p> In multiline mode the expressions <tt>^</tt> and <tt>$</tt> match
4.824 + * just after or just before, respectively, a line terminator or the end of
4.825 + * the input sequence. By default these expressions only match at the
4.826 + * beginning and the end of the entire input sequence.
4.827 + *
4.828 + * <p> Multiline mode can also be enabled via the embedded flag
4.829 + * expression <tt>(?m)</tt>. </p>
4.830 + */
4.831 + public static final int MULTILINE = 0x08;
4.832 +
4.833 + /**
4.834 + * Enables literal parsing of the pattern.
4.835 + *
4.836 + * <p> When this flag is specified then the input string that specifies
4.837 + * the pattern is treated as a sequence of literal characters.
4.838 + * Metacharacters or escape sequences in the input sequence will be
4.839 + * given no special meaning.
4.840 + *
4.841 + * <p>The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact on
4.842 + * matching when used in conjunction with this flag. The other flags
4.843 + * become superfluous.
4.844 + *
4.845 + * <p> There is no embedded flag character for enabling literal parsing.
4.846 + * @since 1.5
4.847 + */
4.848 + public static final int LITERAL = 0x10;
4.849 +
4.850 + /**
4.851 + * Enables dotall mode.
4.852 + *
4.853 + * <p> In dotall mode, the expression <tt>.</tt> matches any character,
4.854 + * including a line terminator. By default this expression does not match
4.855 + * line terminators.
4.856 + *
4.857 + * <p> Dotall mode can also be enabled via the embedded flag
4.858 + * expression <tt>(?s)</tt>. (The <tt>s</tt> is a mnemonic for
4.859 + * "single-line" mode, which is what this is called in Perl.) </p>
4.860 + */
4.861 + public static final int DOTALL = 0x20;
4.862 +
4.863 + /**
4.864 + * Enables Unicode-aware case folding.
4.865 + *
4.866 + * <p> When this flag is specified then case-insensitive matching, when
4.867 + * enabled by the {@link #CASE_INSENSITIVE} flag, is done in a manner
4.868 + * consistent with the Unicode Standard. By default, case-insensitive
4.869 + * matching assumes that only characters in the US-ASCII charset are being
4.870 + * matched.
4.871 + *
4.872 + * <p> Unicode-aware case folding can also be enabled via the embedded flag
4.873 + * expression <tt>(?u)</tt>.
4.874 + *
4.875 + * <p> Specifying this flag may impose a performance penalty. </p>
4.876 + */
4.877 + public static final int UNICODE_CASE = 0x40;
4.878 +
4.879 + /**
4.880 + * Enables canonical equivalence.
4.881 + *
4.882 + * <p> When this flag is specified then two characters will be considered
4.883 + * to match if, and only if, their full canonical decompositions match.
4.884 + * The expression <tt>"a\u030A"</tt>, for example, will match the
4.885 + * string <tt>"\u00E5"</tt> when this flag is specified. By default,
4.886 + * matching does not take canonical equivalence into account.
4.887 + *
4.888 + * <p> There is no embedded flag character for enabling canonical
4.889 + * equivalence.
4.890 + *
4.891 + * <p> Specifying this flag may impose a performance penalty. </p>
4.892 + */
4.893 + public static final int CANON_EQ = 0x80;
4.894 +
4.895 + /**
4.896 + * Enables the Unicode version of <i>Predefined character classes</i> and
4.897 + * <i>POSIX character classes</i>.
4.898 + *
4.899 + * <p> When this flag is specified then the (US-ASCII only)
4.900 + * <i>Predefined character classes</i> and <i>POSIX character classes</i>
4.901 + * are in conformance with
4.902 + * <a href="http://www.unicode.org/reports/tr18/"><i>Unicode Technical
4.903 + * Standard #18: Unicode Regular Expression</i></a>
4.904 + * <i>Annex C: Compatibility Properties</i>.
4.905 + * <p>
4.906 + * The UNICODE_CHARACTER_CLASS mode can also be enabled via the embedded
4.907 + * flag expression <tt>(?U)</tt>.
4.908 + * <p>
4.909 + * The flag implies UNICODE_CASE, that is, it enables Unicode-aware case
4.910 + * folding.
4.911 + * <p>
4.912 + * Specifying this flag may impose a performance penalty. </p>
4.913 + * @since 1.7
4.914 + */
4.915 + public static final int UNICODE_CHARACTER_CLASS = 0x100;
4.916 +
4.917 + /* Pattern has only two serialized components: The pattern string
4.918 + * and the flags, which are all that is needed to recompile the pattern
4.919 + * when it is deserialized.
4.920 + */
4.921 +
4.922 + /** use serialVersionUID from Merlin b59 for interoperability */
4.923 + private static final long serialVersionUID = 5073258162644648461L;
4.924 +
4.925 + /**
4.926 + * The original regular-expression pattern string.
4.927 + *
4.928 + * @serial
4.929 + */
4.930 + private String pattern;
4.931 +
4.932 + /**
4.933 + * The original pattern flags.
4.934 + *
4.935 + * @serial
4.936 + */
4.937 + private int flags;
4.938 +
4.939 + /**
4.940 + * Boolean indicating this Pattern is compiled; this is necessary in order
4.941 + * to lazily compile deserialized Patterns.
4.942 + */
4.943 + private transient volatile boolean compiled = false;
4.944 +
4.945 + /**
4.946 + * The normalized pattern string.
4.947 + */
4.948 + private transient String normalizedPattern;
4.949 +
4.950 + /**
4.951 + * The starting point of state machine for the find operation. This allows
4.952 + * a match to start anywhere in the input.
4.953 + */
4.954 + transient Node root;
4.955 +
4.956 + /**
4.957 + * The root of object tree for a match operation. The pattern is matched
4.958 + * at the beginning. This may include a find that uses BnM or a First
4.959 + * node.
4.960 + */
4.961 + transient Node matchRoot;
4.962 +
4.963 + /**
4.964 + * Temporary storage used by parsing pattern slice.
4.965 + */
4.966 + transient int[] buffer;
4.967 +
4.968 + /**
4.969 + * Map the "name" of the "named capturing group" to its group id
4.970 + * node.
4.971 + */
4.972 + transient volatile Map<String, Integer> namedGroups;
4.973 +
4.974 + /**
4.975 + * Temporary storage used while parsing group references.
4.976 + */
4.977 + transient GroupHead[] groupNodes;
4.978 +
4.979 + /**
4.980 + * Temporary null terminated code point array used by pattern compiling.
4.981 + */
4.982 + private transient int[] temp;
4.983 +
4.984 + /**
4.985 + * The number of capturing groups in this Pattern. Used by matchers to
4.986 + * allocate storage needed to perform a match.
4.987 + */
4.988 + transient int capturingGroupCount;
4.989 +
4.990 + /**
4.991 + * The local variable count used by parsing tree. Used by matchers to
4.992 + * allocate storage needed to perform a match.
4.993 + */
4.994 + transient int localCount;
4.995 +
4.996 + /**
4.997 + * Index into the pattern string that keeps track of how much has been
4.998 + * parsed.
4.999 + */
4.1000 + private transient int cursor;
4.1001 +
4.1002 + /**
4.1003 + * Holds the length of the pattern string.
4.1004 + */
4.1005 + private transient int patternLength;
4.1006 +
4.1007 + /**
4.1008 + * If the Start node might possibly match supplementary characters.
4.1009 + * It is set to true during compiling if
4.1010 + * (1) There is supplementary char in pattern, or
4.1011 + * (2) There is complement node of Category or Block
4.1012 + */
4.1013 + private transient boolean hasSupplementary;
4.1014 +
4.1015 + /**
4.1016 + * Compiles the given regular expression into a pattern. </p>
4.1017 + *
4.1018 + * @param regex
4.1019 + * The expression to be compiled
4.1020 + *
4.1021 + * @throws PatternSyntaxException
4.1022 + * If the expression's syntax is invalid
4.1023 + */
4.1024 + public static Pattern compile(String regex) {
4.1025 + return new Pattern(regex, 0);
4.1026 + }
4.1027 +
4.1028 + /**
4.1029 + * Compiles the given regular expression into a pattern with the given
4.1030 + * flags. </p>
4.1031 + *
4.1032 + * @param regex
4.1033 + * The expression to be compiled
4.1034 + *
4.1035 + * @param flags
4.1036 + * Match flags, a bit mask that may include
4.1037 + * {@link #CASE_INSENSITIVE}, {@link #MULTILINE}, {@link #DOTALL},
4.1038 + * {@link #UNICODE_CASE}, {@link #CANON_EQ}, {@link #UNIX_LINES},
4.1039 + * {@link #LITERAL}, {@link #UNICODE_CHARACTER_CLASS}
4.1040 + * and {@link #COMMENTS}
4.1041 + *
4.1042 + * @throws IllegalArgumentException
4.1043 + * If bit values other than those corresponding to the defined
4.1044 + * match flags are set in <tt>flags</tt>
4.1045 + *
4.1046 + * @throws PatternSyntaxException
4.1047 + * If the expression's syntax is invalid
4.1048 + */
4.1049 + public static Pattern compile(String regex, int flags) {
4.1050 + return new Pattern(regex, flags);
4.1051 + }
4.1052 +
4.1053 + /**
4.1054 + * Returns the regular expression from which this pattern was compiled.
4.1055 + * </p>
4.1056 + *
4.1057 + * @return The source of this pattern
4.1058 + */
4.1059 + public String pattern() {
4.1060 + return pattern;
4.1061 + }
4.1062 +
4.1063 + /**
4.1064 + * <p>Returns the string representation of this pattern. This
4.1065 + * is the regular expression from which this pattern was
4.1066 + * compiled.</p>
4.1067 + *
4.1068 + * @return The string representation of this pattern
4.1069 + * @since 1.5
4.1070 + */
4.1071 + public String toString() {
4.1072 + return pattern;
4.1073 + }
4.1074 +
4.1075 + /**
4.1076 + * Creates a matcher that will match the given input against this pattern.
4.1077 + * </p>
4.1078 + *
4.1079 + * @param input
4.1080 + * The character sequence to be matched
4.1081 + *
4.1082 + * @return A new matcher for this pattern
4.1083 + */
4.1084 + public Matcher matcher(CharSequence input) {
4.1085 + if (!compiled) {
4.1086 + synchronized(this) {
4.1087 + if (!compiled)
4.1088 + compile();
4.1089 + }
4.1090 + }
4.1091 + Matcher m = new Matcher(this, input);
4.1092 + return m;
4.1093 + }
4.1094 +
4.1095 + /**
4.1096 + * Returns this pattern's match flags. </p>
4.1097 + *
4.1098 + * @return The match flags specified when this pattern was compiled
4.1099 + */
4.1100 + public int flags() {
4.1101 + return flags;
4.1102 + }
4.1103 +
4.1104 + /**
4.1105 + * Compiles the given regular expression and attempts to match the given
4.1106 + * input against it.
4.1107 + *
4.1108 + * <p> An invocation of this convenience method of the form
4.1109 + *
4.1110 + * <blockquote><pre>
4.1111 + * Pattern.matches(regex, input);</pre></blockquote>
4.1112 + *
4.1113 + * behaves in exactly the same way as the expression
4.1114 + *
4.1115 + * <blockquote><pre>
4.1116 + * Pattern.compile(regex).matcher(input).matches()</pre></blockquote>
4.1117 + *
4.1118 + * <p> If a pattern is to be used multiple times, compiling it once and reusing
4.1119 + * it will be more efficient than invoking this method each time. </p>
4.1120 + *
4.1121 + * @param regex
4.1122 + * The expression to be compiled
4.1123 + *
4.1124 + * @param input
4.1125 + * The character sequence to be matched
4.1126 + *
4.1127 + * @throws PatternSyntaxException
4.1128 + * If the expression's syntax is invalid
4.1129 + */
4.1130 + public static boolean matches(String regex, CharSequence input) {
4.1131 + Pattern p = Pattern.compile(regex);
4.1132 + Matcher m = p.matcher(input);
4.1133 + return m.matches();
4.1134 + }
4.1135 +
4.1136 + /**
4.1137 + * Splits the given input sequence around matches of this pattern.
4.1138 + *
4.1139 + * <p> The array returned by this method contains each substring of the
4.1140 + * input sequence that is terminated by another subsequence that matches
4.1141 + * this pattern or is terminated by the end of the input sequence. The
4.1142 + * substrings in the array are in the order in which they occur in the
4.1143 + * input. If this pattern does not match any subsequence of the input then
4.1144 + * the resulting array has just one element, namely the input sequence in
4.1145 + * string form.
4.1146 + *
4.1147 + * <p> The <tt>limit</tt> parameter controls the number of times the
4.1148 + * pattern is applied and therefore affects the length of the resulting
4.1149 + * array. If the limit <i>n</i> is greater than zero then the pattern
4.1150 + * will be applied at most <i>n</i> - 1 times, the array's
4.1151 + * length will be no greater than <i>n</i>, and the array's last entry
4.1152 + * will contain all input beyond the last matched delimiter. If <i>n</i>
4.1153 + * is non-positive then the pattern will be applied as many times as
4.1154 + * possible and the array can have any length. If <i>n</i> is zero then
4.1155 + * the pattern will be applied as many times as possible, the array can
4.1156 + * have any length, and trailing empty strings will be discarded.
4.1157 + *
4.1158 + * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
4.1159 + * results with these parameters:
4.1160 + *
4.1161 + * <blockquote><table cellpadding=1 cellspacing=0
4.1162 + * summary="Split examples showing regex, limit, and result">
4.1163 + * <tr><th><P align="left"><i>Regex </i></th>
4.1164 + * <th><P align="left"><i>Limit </i></th>
4.1165 + * <th><P align="left"><i>Result </i></th></tr>
4.1166 + * <tr><td align=center>:</td>
4.1167 + * <td align=center>2</td>
4.1168 + * <td><tt>{ "boo", "and:foo" }</tt></td></tr>
4.1169 + * <tr><td align=center>:</td>
4.1170 + * <td align=center>5</td>
4.1171 + * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
4.1172 + * <tr><td align=center>:</td>
4.1173 + * <td align=center>-2</td>
4.1174 + * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
4.1175 + * <tr><td align=center>o</td>
4.1176 + * <td align=center>5</td>
4.1177 + * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
4.1178 + * <tr><td align=center>o</td>
4.1179 + * <td align=center>-2</td>
4.1180 + * <td><tt>{ "b", "", ":and:f", "", "" }</tt></td></tr>
4.1181 + * <tr><td align=center>o</td>
4.1182 + * <td align=center>0</td>
4.1183 + * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
4.1184 + * </table></blockquote>
4.1185 + *
4.1186 + *
4.1187 + * @param input
4.1188 + * The character sequence to be split
4.1189 + *
4.1190 + * @param limit
4.1191 + * The result threshold, as described above
4.1192 + *
4.1193 + * @return The array of strings computed by splitting the input
4.1194 + * around matches of this pattern
4.1195 + */
4.1196 + public String[] split(CharSequence input, int limit) {
4.1197 + int index = 0;
4.1198 + boolean matchLimited = limit > 0;
4.1199 + ArrayList<String> matchList = new ArrayList<>();
4.1200 + Matcher m = matcher(input);
4.1201 +
4.1202 + // Add segments before each match found
4.1203 + while(m.find()) {
4.1204 + if (!matchLimited || matchList.size() < limit - 1) {
4.1205 + String match = input.subSequence(index, m.start()).toString();
4.1206 + matchList.add(match);
4.1207 + index = m.end();
4.1208 + } else if (matchList.size() == limit - 1) { // last one
4.1209 + String match = input.subSequence(index,
4.1210 + input.length()).toString();
4.1211 + matchList.add(match);
4.1212 + index = m.end();
4.1213 + }
4.1214 + }
4.1215 +
4.1216 + // If no match was found, return this
4.1217 + if (index == 0)
4.1218 + return new String[] {input.toString()};
4.1219 +
4.1220 + // Add remaining segment
4.1221 + if (!matchLimited || matchList.size() < limit)
4.1222 + matchList.add(input.subSequence(index, input.length()).toString());
4.1223 +
4.1224 + // Construct result
4.1225 + int resultSize = matchList.size();
4.1226 + if (limit == 0)
4.1227 + while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
4.1228 + resultSize--;
4.1229 + String[] result = new String[resultSize];
4.1230 + return matchList.subList(0, resultSize).toArray(result);
4.1231 + }
4.1232 +
4.1233 + /**
4.1234 + * Splits the given input sequence around matches of this pattern.
4.1235 + *
4.1236 + * <p> This method works as if by invoking the two-argument {@link
4.1237 + * #split(java.lang.CharSequence, int) split} method with the given input
4.1238 + * sequence and a limit argument of zero. Trailing empty strings are
4.1239 + * therefore not included in the resulting array. </p>
4.1240 + *
4.1241 + * <p> The input <tt>"boo:and:foo"</tt>, for example, yields the following
4.1242 + * results with these expressions:
4.1243 + *
4.1244 + * <blockquote><table cellpadding=1 cellspacing=0
4.1245 + * summary="Split examples showing regex and result">
4.1246 + * <tr><th><P align="left"><i>Regex </i></th>
4.1247 + * <th><P align="left"><i>Result</i></th></tr>
4.1248 + * <tr><td align=center>:</td>
4.1249 + * <td><tt>{ "boo", "and", "foo" }</tt></td></tr>
4.1250 + * <tr><td align=center>o</td>
4.1251 + * <td><tt>{ "b", "", ":and:f" }</tt></td></tr>
4.1252 + * </table></blockquote>
4.1253 + *
4.1254 + *
4.1255 + * @param input
4.1256 + * The character sequence to be split
4.1257 + *
4.1258 + * @return The array of strings computed by splitting the input
4.1259 + * around matches of this pattern
4.1260 + */
4.1261 + public String[] split(CharSequence input) {
4.1262 + return split(input, 0);
4.1263 + }
4.1264 +
4.1265 + /**
4.1266 + * Returns a literal pattern <code>String</code> for the specified
4.1267 + * <code>String</code>.
4.1268 + *
4.1269 + * <p>This method produces a <code>String</code> that can be used to
4.1270 + * create a <code>Pattern</code> that would match the string
4.1271 + * <code>s</code> as if it were a literal pattern.</p> Metacharacters
4.1272 + * or escape sequences in the input sequence will be given no special
4.1273 + * meaning.
4.1274 + *
4.1275 + * @param s The string to be literalized
4.1276 + * @return A literal string replacement
4.1277 + * @since 1.5
4.1278 + */
4.1279 + public static String quote(String s) {
4.1280 + int slashEIndex = s.indexOf("\\E");
4.1281 + if (slashEIndex == -1)
4.1282 + return "\\Q" + s + "\\E";
4.1283 +
4.1284 + StringBuilder sb = new StringBuilder(s.length() * 2);
4.1285 + sb.append("\\Q");
4.1286 + slashEIndex = 0;
4.1287 + int current = 0;
4.1288 + while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
4.1289 + sb.append(s.substring(current, slashEIndex));
4.1290 + current = slashEIndex + 2;
4.1291 + sb.append("\\E\\\\E\\Q");
4.1292 + }
4.1293 + sb.append(s.substring(current, s.length()));
4.1294 + sb.append("\\E");
4.1295 + return sb.toString();
4.1296 + }
4.1297 +
4.1298 + /**
4.1299 + * Recompile the Pattern instance from a stream. The original pattern
4.1300 + * string is read in and the object tree is recompiled from it.
4.1301 + */
4.1302 + private void readObject(java.io.ObjectInputStream s)
4.1303 + throws java.io.IOException, ClassNotFoundException {
4.1304 +
4.1305 + // Read in all fields
4.1306 + s.defaultReadObject();
4.1307 +
4.1308 + // Initialize counts
4.1309 + capturingGroupCount = 1;
4.1310 + localCount = 0;
4.1311 +
4.1312 + // if length > 0, the Pattern is lazily compiled
4.1313 + compiled = false;
4.1314 + if (pattern.length() == 0) {
4.1315 + root = new Start(lastAccept);
4.1316 + matchRoot = lastAccept;
4.1317 + compiled = true;
4.1318 + }
4.1319 + }
4.1320 +
4.1321 + /**
4.1322 + * This private constructor is used to create all Patterns. The pattern
4.1323 + * string and match flags are all that is needed to completely describe
4.1324 + * a Pattern. An empty pattern string results in an object tree with
4.1325 + * only a Start node and a LastNode node.
4.1326 + */
4.1327 + private Pattern(String p, int f) {
4.1328 + pattern = p;
4.1329 + flags = f;
4.1330 +
4.1331 + // to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
4.1332 + if ((flags & UNICODE_CHARACTER_CLASS) != 0)
4.1333 + flags |= UNICODE_CASE;
4.1334 +
4.1335 + // Reset group index count
4.1336 + capturingGroupCount = 1;
4.1337 + localCount = 0;
4.1338 +
4.1339 + if (pattern.length() > 0) {
4.1340 + compile();
4.1341 + } else {
4.1342 + root = new Start(lastAccept);
4.1343 + matchRoot = lastAccept;
4.1344 + }
4.1345 + }
4.1346 +
4.1347 + /**
4.1348 + * The pattern is converted to normalizedD form and then a pure group
4.1349 + * is constructed to match canonical equivalences of the characters.
4.1350 + */
4.1351 + private void normalize() {
4.1352 + boolean inCharClass = false;
4.1353 + int lastCodePoint = -1;
4.1354 +
4.1355 + // Convert pattern into normalizedD form
4.1356 + normalizedPattern = Normalizer.normalize(pattern, Normalizer.Form.NFD);
4.1357 + patternLength = normalizedPattern.length();
4.1358 +
4.1359 + // Modify pattern to match canonical equivalences
4.1360 + StringBuilder newPattern = new StringBuilder(patternLength);
4.1361 + for(int i=0; i<patternLength; ) {
4.1362 + int c = normalizedPattern.codePointAt(i);
4.1363 + StringBuilder sequenceBuffer;
4.1364 + if ((Character.getType(c) == Character.NON_SPACING_MARK)
4.1365 + && (lastCodePoint != -1)) {
4.1366 + sequenceBuffer = new StringBuilder();
4.1367 + sequenceBuffer.appendCodePoint(lastCodePoint);
4.1368 + sequenceBuffer.appendCodePoint(c);
4.1369 + while(Character.getType(c) == Character.NON_SPACING_MARK) {
4.1370 + i += Character.charCount(c);
4.1371 + if (i >= patternLength)
4.1372 + break;
4.1373 + c = normalizedPattern.codePointAt(i);
4.1374 + sequenceBuffer.appendCodePoint(c);
4.1375 + }
4.1376 + String ea = produceEquivalentAlternation(
4.1377 + sequenceBuffer.toString());
4.1378 + newPattern.setLength(newPattern.length()-Character.charCount(lastCodePoint));
4.1379 + newPattern.append("(?:").append(ea).append(")");
4.1380 + } else if (c == '[' && lastCodePoint != '\\') {
4.1381 + i = normalizeCharClass(newPattern, i);
4.1382 + } else {
4.1383 + newPattern.appendCodePoint(c);
4.1384 + }
4.1385 + lastCodePoint = c;
4.1386 + i += Character.charCount(c);
4.1387 + }
4.1388 + normalizedPattern = newPattern.toString();
4.1389 + }
4.1390 +
4.1391 + /**
4.1392 + * Complete the character class being parsed and add a set
4.1393 + * of alternations to it that will match the canonical equivalences
4.1394 + * of the characters within the class.
4.1395 + */
4.1396 + private int normalizeCharClass(StringBuilder newPattern, int i) {
4.1397 + StringBuilder charClass = new StringBuilder();
4.1398 + StringBuilder eq = null;
4.1399 + int lastCodePoint = -1;
4.1400 + String result;
4.1401 +
4.1402 + i++;
4.1403 + charClass.append("[");
4.1404 + while(true) {
4.1405 + int c = normalizedPattern.codePointAt(i);
4.1406 + StringBuilder sequenceBuffer;
4.1407 +
4.1408 + if (c == ']' && lastCodePoint != '\\') {
4.1409 + charClass.append((char)c);
4.1410 + break;
4.1411 + } else if (Character.getType(c) == Character.NON_SPACING_MARK) {
4.1412 + sequenceBuffer = new StringBuilder();
4.1413 + sequenceBuffer.appendCodePoint(lastCodePoint);
4.1414 + while(Character.getType(c) == Character.NON_SPACING_MARK) {
4.1415 + sequenceBuffer.appendCodePoint(c);
4.1416 + i += Character.charCount(c);
4.1417 + if (i >= normalizedPattern.length())
4.1418 + break;
4.1419 + c = normalizedPattern.codePointAt(i);
4.1420 + }
4.1421 + String ea = produceEquivalentAlternation(
4.1422 + sequenceBuffer.toString());
4.1423 +
4.1424 + charClass.setLength(charClass.length()-Character.charCount(lastCodePoint));
4.1425 + if (eq == null)
4.1426 + eq = new StringBuilder();
4.1427 + eq.append('|');
4.1428 + eq.append(ea);
4.1429 + } else {
4.1430 + charClass.appendCodePoint(c);
4.1431 + i++;
4.1432 + }
4.1433 + if (i == normalizedPattern.length())
4.1434 + throw error("Unclosed character class");
4.1435 + lastCodePoint = c;
4.1436 + }
4.1437 +
4.1438 + if (eq != null) {
4.1439 + result = "(?:"+charClass.toString()+eq.toString()+")";
4.1440 + } else {
4.1441 + result = charClass.toString();
4.1442 + }
4.1443 +
4.1444 + newPattern.append(result);
4.1445 + return i;
4.1446 + }
4.1447 +
4.1448 + /**
4.1449 + * Given a specific sequence composed of a regular character and
4.1450 + * combining marks that follow it, produce the alternation that will
4.1451 + * match all canonical equivalences of that sequence.
4.1452 + */
4.1453 + private String produceEquivalentAlternation(String source) {
4.1454 + int len = countChars(source, 0, 1);
4.1455 + if (source.length() == len)
4.1456 + // source has one character.
4.1457 + return source;
4.1458 +
4.1459 + String base = source.substring(0,len);
4.1460 + String combiningMarks = source.substring(len);
4.1461 +
4.1462 + String[] perms = producePermutations(combiningMarks);
4.1463 + StringBuilder result = new StringBuilder(source);
4.1464 +
4.1465 + // Add combined permutations
4.1466 + for(int x=0; x<perms.length; x++) {
4.1467 + String next = base + perms[x];
4.1468 + if (x>0)
4.1469 + result.append("|"+next);
4.1470 + next = composeOneStep(next);
4.1471 + if (next != null)
4.1472 + result.append("|"+produceEquivalentAlternation(next));
4.1473 + }
4.1474 + return result.toString();
4.1475 + }
4.1476 +
4.1477 + /**
4.1478 + * Returns an array of strings that have all the possible
4.1479 + * permutations of the characters in the input string.
4.1480 + * This is used to get a list of all possible orderings
4.1481 + * of a set of combining marks. Note that some of the permutations
4.1482 + * are invalid because of combining class collisions, and these
4.1483 + * possibilities must be removed because they are not canonically
4.1484 + * equivalent.
4.1485 + */
4.1486 + private String[] producePermutations(String input) {
4.1487 + if (input.length() == countChars(input, 0, 1))
4.1488 + return new String[] {input};
4.1489 +
4.1490 + if (input.length() == countChars(input, 0, 2)) {
4.1491 + int c0 = Character.codePointAt(input, 0);
4.1492 + int c1 = Character.codePointAt(input, Character.charCount(c0));
4.1493 + if (getClass(c1) == getClass(c0)) {
4.1494 + return new String[] {input};
4.1495 + }
4.1496 + String[] result = new String[2];
4.1497 + result[0] = input;
4.1498 + StringBuilder sb = new StringBuilder(2);
4.1499 + sb.appendCodePoint(c1);
4.1500 + sb.appendCodePoint(c0);
4.1501 + result[1] = sb.toString();
4.1502 + return result;
4.1503 + }
4.1504 +
4.1505 + int length = 1;
4.1506 + int nCodePoints = countCodePoints(input);
4.1507 + for(int x=1; x<nCodePoints; x++)
4.1508 + length = length * (x+1);
4.1509 +
4.1510 + String[] temp = new String[length];
4.1511 +
4.1512 + int combClass[] = new int[nCodePoints];
4.1513 + for(int x=0, i=0; x<nCodePoints; x++) {
4.1514 + int c = Character.codePointAt(input, i);
4.1515 + combClass[x] = getClass(c);
4.1516 + i += Character.charCount(c);
4.1517 + }
4.1518 +
4.1519 + // For each char, take it out and add the permutations
4.1520 + // of the remaining chars
4.1521 + int index = 0;
4.1522 + int len;
4.1523 + // offset maintains the index in code units.
4.1524 +loop: for(int x=0, offset=0; x<nCodePoints; x++, offset+=len) {
4.1525 + len = countChars(input, offset, 1);
4.1526 + boolean skip = false;
4.1527 + for(int y=x-1; y>=0; y--) {
4.1528 + if (combClass[y] == combClass[x]) {
4.1529 + continue loop;
4.1530 + }
4.1531 + }
4.1532 + StringBuilder sb = new StringBuilder(input);
4.1533 + String otherChars = sb.delete(offset, offset+len).toString();
4.1534 + String[] subResult = producePermutations(otherChars);
4.1535 +
4.1536 + String prefix = input.substring(offset, offset+len);
4.1537 + for(int y=0; y<subResult.length; y++)
4.1538 + temp[index++] = prefix + subResult[y];
4.1539 + }
4.1540 + String[] result = new String[index];
4.1541 + for (int x=0; x<index; x++)
4.1542 + result[x] = temp[x];
4.1543 + return result;
4.1544 + }
4.1545 +
4.1546 + private int getClass(int c) {
4.1547 + return sun.text.Normalizer.getCombiningClass(c);
4.1548 + }
4.1549 +
4.1550 + /**
4.1551 + * Attempts to compose input by combining the first character
4.1552 + * with the first combining mark following it. Returns a String
4.1553 + * that is the composition of the leading character with its first
4.1554 + * combining mark followed by the remaining combining marks. Returns
4.1555 + * null if the first two characters cannot be further composed.
4.1556 + */
4.1557 + private String composeOneStep(String input) {
4.1558 + int len = countChars(input, 0, 2);
4.1559 + String firstTwoCharacters = input.substring(0, len);
4.1560 + String result = Normalizer.normalize(firstTwoCharacters, Normalizer.Form.NFC);
4.1561 +
4.1562 + if (result.equals(firstTwoCharacters))
4.1563 + return null;
4.1564 + else {
4.1565 + String remainder = input.substring(len);
4.1566 + return result + remainder;
4.1567 + }
4.1568 + }
4.1569 +
4.1570 + /**
4.1571 + * Preprocess any \Q...\E sequences in `temp', meta-quoting them.
4.1572 + * See the description of `quotemeta' in perlfunc(1).
4.1573 + */
4.1574 + private void RemoveQEQuoting() {
4.1575 + final int pLen = patternLength;
4.1576 + int i = 0;
4.1577 + while (i < pLen-1) {
4.1578 + if (temp[i] != '\\')
4.1579 + i += 1;
4.1580 + else if (temp[i + 1] != 'Q')
4.1581 + i += 2;
4.1582 + else
4.1583 + break;
4.1584 + }
4.1585 + if (i >= pLen - 1) // No \Q sequence found
4.1586 + return;
4.1587 + int j = i;
4.1588 + i += 2;
4.1589 + int[] newtemp = new int[j + 2*(pLen-i) + 2];
4.1590 + System.arraycopy(temp, 0, newtemp, 0, j);
4.1591 +
4.1592 + boolean inQuote = true;
4.1593 + while (i < pLen) {
4.1594 + int c = temp[i++];
4.1595 + if (! ASCII.isAscii(c) || ASCII.isAlnum(c)) {
4.1596 + newtemp[j++] = c;
4.1597 + } else if (c != '\\') {
4.1598 + if (inQuote) newtemp[j++] = '\\';
4.1599 + newtemp[j++] = c;
4.1600 + } else if (inQuote) {
4.1601 + if (temp[i] == 'E') {
4.1602 + i++;
4.1603 + inQuote = false;
4.1604 + } else {
4.1605 + newtemp[j++] = '\\';
4.1606 + newtemp[j++] = '\\';
4.1607 + }
4.1608 + } else {
4.1609 + if (temp[i] == 'Q') {
4.1610 + i++;
4.1611 + inQuote = true;
4.1612 + } else {
4.1613 + newtemp[j++] = c;
4.1614 + if (i != pLen)
4.1615 + newtemp[j++] = temp[i++];
4.1616 + }
4.1617 + }
4.1618 + }
4.1619 +
4.1620 + patternLength = j;
4.1621 + temp = Arrays.copyOf(newtemp, j + 2); // double zero termination
4.1622 + }
4.1623 +
4.1624 + /**
4.1625 + * Copies regular expression to an int array and invokes the parsing
4.1626 + * of the expression which will create the object tree.
4.1627 + */
4.1628 + private void compile() {
4.1629 + // Handle canonical equivalences
4.1630 + if (has(CANON_EQ) && !has(LITERAL)) {
4.1631 + normalize();
4.1632 + } else {
4.1633 + normalizedPattern = pattern;
4.1634 + }
4.1635 + patternLength = normalizedPattern.length();
4.1636 +
4.1637 + // Copy pattern to int array for convenience
4.1638 + // Use double zero to terminate pattern
4.1639 + temp = new int[patternLength + 2];
4.1640 +
4.1641 + hasSupplementary = false;
4.1642 + int c, count = 0;
4.1643 + // Convert all chars into code points
4.1644 + for (int x = 0; x < patternLength; x += Character.charCount(c)) {
4.1645 + c = normalizedPattern.codePointAt(x);
4.1646 + if (isSupplementary(c)) {
4.1647 + hasSupplementary = true;
4.1648 + }
4.1649 + temp[count++] = c;
4.1650 + }
4.1651 +
4.1652 + patternLength = count; // patternLength now in code points
4.1653 +
4.1654 + if (! has(LITERAL))
4.1655 + RemoveQEQuoting();
4.1656 +
4.1657 + // Allocate all temporary objects here.
4.1658 + buffer = new int[32];
4.1659 + groupNodes = new GroupHead[10];
4.1660 + namedGroups = null;
4.1661 +
4.1662 + if (has(LITERAL)) {
4.1663 + // Literal pattern handling
4.1664 + matchRoot = newSlice(temp, patternLength, hasSupplementary);
4.1665 + matchRoot.next = lastAccept;
4.1666 + } else {
4.1667 + // Start recursive descent parsing
4.1668 + matchRoot = expr(lastAccept);
4.1669 + // Check extra pattern characters
4.1670 + if (patternLength != cursor) {
4.1671 + if (peek() == ')') {
4.1672 + throw error("Unmatched closing ')'");
4.1673 + } else {
4.1674 + throw error("Unexpected internal error");
4.1675 + }
4.1676 + }
4.1677 + }
4.1678 +
4.1679 + // Peephole optimization
4.1680 + if (matchRoot instanceof Slice) {
4.1681 + root = BnM.optimize(matchRoot);
4.1682 + if (root == matchRoot) {
4.1683 + root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
4.1684 + }
4.1685 + } else if (matchRoot instanceof Begin || matchRoot instanceof First) {
4.1686 + root = matchRoot;
4.1687 + } else {
4.1688 + root = hasSupplementary ? new StartS(matchRoot) : new Start(matchRoot);
4.1689 + }
4.1690 +
4.1691 + // Release temporary storage
4.1692 + temp = null;
4.1693 + buffer = null;
4.1694 + groupNodes = null;
4.1695 + patternLength = 0;
4.1696 + compiled = true;
4.1697 + }
4.1698 +
4.1699 + Map<String, Integer> namedGroups() {
4.1700 + if (namedGroups == null)
4.1701 + namedGroups = new HashMap<>(2);
4.1702 + return namedGroups;
4.1703 + }
4.1704 +
4.1705 + /**
4.1706 + * Used to print out a subtree of the Pattern to help with debugging.
4.1707 + */
4.1708 + private static void printObjectTree(Node node) {
4.1709 + while(node != null) {
4.1710 + if (node instanceof Prolog) {
4.1711 + System.out.println(node);
4.1712 + printObjectTree(((Prolog)node).loop);
4.1713 + System.out.println("**** end contents prolog loop");
4.1714 + } else if (node instanceof Loop) {
4.1715 + System.out.println(node);
4.1716 + printObjectTree(((Loop)node).body);
4.1717 + System.out.println("**** end contents Loop body");
4.1718 + } else if (node instanceof Curly) {
4.1719 + System.out.println(node);
4.1720 + printObjectTree(((Curly)node).atom);
4.1721 + System.out.println("**** end contents Curly body");
4.1722 + } else if (node instanceof GroupCurly) {
4.1723 + System.out.println(node);
4.1724 + printObjectTree(((GroupCurly)node).atom);
4.1725 + System.out.println("**** end contents GroupCurly body");
4.1726 + } else if (node instanceof GroupTail) {
4.1727 + System.out.println(node);
4.1728 + System.out.println("Tail next is "+node.next);
4.1729 + return;
4.1730 + } else {
4.1731 + System.out.println(node);
4.1732 + }
4.1733 + node = node.next;
4.1734 + if (node != null)
4.1735 + System.out.println("->next:");
4.1736 + if (node == Pattern.accept) {
4.1737 + System.out.println("Accept Node");
4.1738 + node = null;
4.1739 + }
4.1740 + }
4.1741 + }
4.1742 +
4.1743 + /**
4.1744 + * Used to accumulate information about a subtree of the object graph
4.1745 + * so that optimizations can be applied to the subtree.
4.1746 + */
4.1747 + static final class TreeInfo {
4.1748 + int minLength;
4.1749 + int maxLength;
4.1750 + boolean maxValid;
4.1751 + boolean deterministic;
4.1752 +
4.1753 + TreeInfo() {
4.1754 + reset();
4.1755 + }
4.1756 + void reset() {
4.1757 + minLength = 0;
4.1758 + maxLength = 0;
4.1759 + maxValid = true;
4.1760 + deterministic = true;
4.1761 + }
4.1762 + }
4.1763 +
4.1764 + /*
4.1765 + * The following private methods are mainly used to improve the
4.1766 + * readability of the code. In order to let the Java compiler easily
4.1767 + * inline them, we should not put many assertions or error checks in them.
4.1768 + */
4.1769 +
4.1770 + /**
4.1771 + * Indicates whether a particular flag is set or not.
4.1772 + */
4.1773 + private boolean has(int f) {
4.1774 + return (flags & f) != 0;
4.1775 + }
4.1776 +
4.1777 + /**
4.1778 + * Match next character, signal error if failed.
4.1779 + */
4.1780 + private void accept(int ch, String s) {
4.1781 + int testChar = temp[cursor++];
4.1782 + if (has(COMMENTS))
4.1783 + testChar = parsePastWhitespace(testChar);
4.1784 + if (ch != testChar) {
4.1785 + throw error(s);
4.1786 + }
4.1787 + }
4.1788 +
4.1789 + /**
4.1790 + * Mark the end of pattern with a specific character.
4.1791 + */
4.1792 + private void mark(int c) {
4.1793 + temp[patternLength] = c;
4.1794 + }
4.1795 +
4.1796 + /**
4.1797 + * Peek the next character, and do not advance the cursor.
4.1798 + */
4.1799 + private int peek() {
4.1800 + int ch = temp[cursor];
4.1801 + if (has(COMMENTS))
4.1802 + ch = peekPastWhitespace(ch);
4.1803 + return ch;
4.1804 + }
4.1805 +
4.1806 + /**
4.1807 + * Read the next character, and advance the cursor by one.
4.1808 + */
4.1809 + private int read() {
4.1810 + int ch = temp[cursor++];
4.1811 + if (has(COMMENTS))
4.1812 + ch = parsePastWhitespace(ch);
4.1813 + return ch;
4.1814 + }
4.1815 +
4.1816 + /**
4.1817 + * Read the next character, and advance the cursor by one,
4.1818 + * ignoring the COMMENTS setting
4.1819 + */
4.1820 + private int readEscaped() {
4.1821 + int ch = temp[cursor++];
4.1822 + return ch;
4.1823 + }
4.1824 +
4.1825 + /**
4.1826 + * Advance the cursor by one, and peek the next character.
4.1827 + */
4.1828 + private int next() {
4.1829 + int ch = temp[++cursor];
4.1830 + if (has(COMMENTS))
4.1831 + ch = peekPastWhitespace(ch);
4.1832 + return ch;
4.1833 + }
4.1834 +
4.1835 + /**
4.1836 + * Advance the cursor by one, and peek the next character,
4.1837 + * ignoring the COMMENTS setting
4.1838 + */
4.1839 + private int nextEscaped() {
4.1840 + int ch = temp[++cursor];
4.1841 + return ch;
4.1842 + }
4.1843 +
4.1844 + /**
4.1845 + * If in xmode peek past whitespace and comments.
4.1846 + */
4.1847 + private int peekPastWhitespace(int ch) {
4.1848 + while (ASCII.isSpace(ch) || ch == '#') {
4.1849 + while (ASCII.isSpace(ch))
4.1850 + ch = temp[++cursor];
4.1851 + if (ch == '#') {
4.1852 + ch = peekPastLine();
4.1853 + }
4.1854 + }
4.1855 + return ch;
4.1856 + }
4.1857 +
4.1858 + /**
4.1859 + * If in xmode parse past whitespace and comments.
4.1860 + */
4.1861 + private int parsePastWhitespace(int ch) {
4.1862 + while (ASCII.isSpace(ch) || ch == '#') {
4.1863 + while (ASCII.isSpace(ch))
4.1864 + ch = temp[cursor++];
4.1865 + if (ch == '#')
4.1866 + ch = parsePastLine();
4.1867 + }
4.1868 + return ch;
4.1869 + }
4.1870 +
4.1871 + /**
4.1872 + * xmode parse past comment to end of line.
4.1873 + */
4.1874 + private int parsePastLine() {
4.1875 + int ch = temp[cursor++];
4.1876 + while (ch != 0 && !isLineSeparator(ch))
4.1877 + ch = temp[cursor++];
4.1878 + return ch;
4.1879 + }
4.1880 +
4.1881 + /**
4.1882 + * xmode peek past comment to end of line.
4.1883 + */
4.1884 + private int peekPastLine() {
4.1885 + int ch = temp[++cursor];
4.1886 + while (ch != 0 && !isLineSeparator(ch))
4.1887 + ch = temp[++cursor];
4.1888 + return ch;
4.1889 + }
4.1890 +
4.1891 + /**
4.1892 + * Determines if character is a line separator in the current mode
4.1893 + */
4.1894 + private boolean isLineSeparator(int ch) {
4.1895 + if (has(UNIX_LINES)) {
4.1896 + return ch == '\n';
4.1897 + } else {
4.1898 + return (ch == '\n' ||
4.1899 + ch == '\r' ||
4.1900 + (ch|1) == '\u2029' ||
4.1901 + ch == '\u0085');
4.1902 + }
4.1903 + }
4.1904 +
4.1905 + /**
4.1906 + * Read the character after the next one, and advance the cursor by two.
4.1907 + */
4.1908 + private int skip() {
4.1909 + int i = cursor;
4.1910 + int ch = temp[i+1];
4.1911 + cursor = i + 2;
4.1912 + return ch;
4.1913 + }
4.1914 +
4.1915 + /**
4.1916 + * Unread one next character, and retreat cursor by one.
4.1917 + */
4.1918 + private void unread() {
4.1919 + cursor--;
4.1920 + }
4.1921 +
4.1922 + /**
4.1923 + * Internal method used for handling all syntax errors. The pattern is
4.1924 + * displayed with a pointer to aid in locating the syntax error.
4.1925 + */
4.1926 + private PatternSyntaxException error(String s) {
4.1927 + return new PatternSyntaxException(s, normalizedPattern, cursor - 1);
4.1928 + }
4.1929 +
4.1930 + /**
4.1931 + * Determines if there is any supplementary character or unpaired
4.1932 + * surrogate in the specified range.
4.1933 + */
4.1934 + private boolean findSupplementary(int start, int end) {
4.1935 + for (int i = start; i < end; i++) {
4.1936 + if (isSupplementary(temp[i]))
4.1937 + return true;
4.1938 + }
4.1939 + return false;
4.1940 + }
4.1941 +
4.1942 + /**
4.1943 + * Determines if the specified code point is a supplementary
4.1944 + * character or unpaired surrogate.
4.1945 + */
4.1946 + private static final boolean isSupplementary(int ch) {
4.1947 + return ch >= Character.MIN_SUPPLEMENTARY_CODE_POINT ||
4.1948 + Character.isSurrogate((char)ch);
4.1949 + }
4.1950 +
4.1951 + /**
4.1952 + * The following methods handle the main parsing. They are sorted
4.1953 + * according to their precedence order, the lowest one first.
4.1954 + */
4.1955 +
4.1956 + /**
4.1957 + * The expression is parsed with branch nodes added for alternations.
4.1958 + * This may be called recursively to parse sub expressions that may
4.1959 + * contain alternations.
4.1960 + */
4.1961 + private Node expr(Node end) {
4.1962 + Node prev = null;
4.1963 + Node firstTail = null;
4.1964 + Node branchConn = null;
4.1965 +
4.1966 + for (;;) {
4.1967 + Node node = sequence(end);
4.1968 + Node nodeTail = root; //double return
4.1969 + if (prev == null) {
4.1970 + prev = node;
4.1971 + firstTail = nodeTail;
4.1972 + } else {
4.1973 + // Branch
4.1974 + if (branchConn == null) {
4.1975 + branchConn = new BranchConn();
4.1976 + branchConn.next = end;
4.1977 + }
4.1978 + if (node == end) {
4.1979 + // if the node returned from sequence() is "end"
4.1980 + // we have an empty expr, set a null atom into
4.1981 + // the branch to indicate to go "next" directly.
4.1982 + node = null;
4.1983 + } else {
4.1984 + // the "tail.next" of each atom goes to branchConn
4.1985 + nodeTail.next = branchConn;
4.1986 + }
4.1987 + if (prev instanceof Branch) {
4.1988 + ((Branch)prev).add(node);
4.1989 + } else {
4.1990 + if (prev == end) {
4.1991 + prev = null;
4.1992 + } else {
4.1993 + // replace the "end" with "branchConn" at its tail.next
4.1994 + // when put the "prev" into the branch as the first atom.
4.1995 + firstTail.next = branchConn;
4.1996 + }
4.1997 + prev = new Branch(prev, node, branchConn);
4.1998 + }
4.1999 + }
4.2000 + if (peek() != '|') {
4.2001 + return prev;
4.2002 + }
4.2003 + next();
4.2004 + }
4.2005 + }
4.2006 +
4.2007 + /**
4.2008 + * Parsing of sequences between alternations.
4.2009 + */
4.2010 + private Node sequence(Node end) {
4.2011 + Node head = null;
4.2012 + Node tail = null;
4.2013 + Node node = null;
4.2014 + LOOP:
4.2015 + for (;;) {
4.2016 + int ch = peek();
4.2017 + switch (ch) {
4.2018 + case '(':
4.2019 + // Because group handles its own closure,
4.2020 + // we need to treat it differently
4.2021 + node = group0();
4.2022 + // Check for comment or flag group
4.2023 + if (node == null)
4.2024 + continue;
4.2025 + if (head == null)
4.2026 + head = node;
4.2027 + else
4.2028 + tail.next = node;
4.2029 + // Double return: Tail was returned in root
4.2030 + tail = root;
4.2031 + continue;
4.2032 + case '[':
4.2033 + node = clazz(true);
4.2034 + break;
4.2035 + case '\\':
4.2036 + ch = nextEscaped();
4.2037 + if (ch == 'p' || ch == 'P') {
4.2038 + boolean oneLetter = true;
4.2039 + boolean comp = (ch == 'P');
4.2040 + ch = next(); // Consume { if present
4.2041 + if (ch != '{') {
4.2042 + unread();
4.2043 + } else {
4.2044 + oneLetter = false;
4.2045 + }
4.2046 + node = family(oneLetter, comp);
4.2047 + } else {
4.2048 + unread();
4.2049 + node = atom();
4.2050 + }
4.2051 + break;
4.2052 + case '^':
4.2053 + next();
4.2054 + if (has(MULTILINE)) {
4.2055 + if (has(UNIX_LINES))
4.2056 + node = new UnixCaret();
4.2057 + else
4.2058 + node = new Caret();
4.2059 + } else {
4.2060 + node = new Begin();
4.2061 + }
4.2062 + break;
4.2063 + case '$':
4.2064 + next();
4.2065 + if (has(UNIX_LINES))
4.2066 + node = new UnixDollar(has(MULTILINE));
4.2067 + else
4.2068 + node = new Dollar(has(MULTILINE));
4.2069 + break;
4.2070 + case '.':
4.2071 + next();
4.2072 + if (has(DOTALL)) {
4.2073 + node = new All();
4.2074 + } else {
4.2075 + if (has(UNIX_LINES))
4.2076 + node = new UnixDot();
4.2077 + else {
4.2078 + node = new Dot();
4.2079 + }
4.2080 + }
4.2081 + break;
4.2082 + case '|':
4.2083 + case ')':
4.2084 + break LOOP;
4.2085 + case ']': // Now interpreting dangling ] and } as literals
4.2086 + case '}':
4.2087 + node = atom();
4.2088 + break;
4.2089 + case '?':
4.2090 + case '*':
4.2091 + case '+':
4.2092 + next();
4.2093 + throw error("Dangling meta character '" + ((char)ch) + "'");
4.2094 + case 0:
4.2095 + if (cursor >= patternLength) {
4.2096 + break LOOP;
4.2097 + }
4.2098 + // Fall through
4.2099 + default:
4.2100 + node = atom();
4.2101 + break;
4.2102 + }
4.2103 +
4.2104 + node = closure(node);
4.2105 +
4.2106 + if (head == null) {
4.2107 + head = tail = node;
4.2108 + } else {
4.2109 + tail.next = node;
4.2110 + tail = node;
4.2111 + }
4.2112 + }
4.2113 + if (head == null) {
4.2114 + return end;
4.2115 + }
4.2116 + tail.next = end;
4.2117 + root = tail; //double return
4.2118 + return head;
4.2119 + }
4.2120 +
4.2121 + /**
4.2122 + * Parse and add a new Single or Slice.
4.2123 + */
4.2124 + private Node atom() {
4.2125 + int first = 0;
4.2126 + int prev = -1;
4.2127 + boolean hasSupplementary = false;
4.2128 + int ch = peek();
4.2129 + for (;;) {
4.2130 + switch (ch) {
4.2131 + case '*':
4.2132 + case '+':
4.2133 + case '?':
4.2134 + case '{':
4.2135 + if (first > 1) {
4.2136 + cursor = prev; // Unwind one character
4.2137 + first--;
4.2138 + }
4.2139 + break;
4.2140 + case '$':
4.2141 + case '.':
4.2142 + case '^':
4.2143 + case '(':
4.2144 + case '[':
4.2145 + case '|':
4.2146 + case ')':
4.2147 + break;
4.2148 + case '\\':
4.2149 + ch = nextEscaped();
4.2150 + if (ch == 'p' || ch == 'P') { // Property
4.2151 + if (first > 0) { // Slice is waiting; handle it first
4.2152 + unread();
4.2153 + break;
4.2154 + } else { // No slice; just return the family node
4.2155 + boolean comp = (ch == 'P');
4.2156 + boolean oneLetter = true;
4.2157 + ch = next(); // Consume { if present
4.2158 + if (ch != '{')
4.2159 + unread();
4.2160 + else
4.2161 + oneLetter = false;
4.2162 + return family(oneLetter, comp);
4.2163 + }
4.2164 + }
4.2165 + unread();
4.2166 + prev = cursor;
4.2167 + ch = escape(false, first == 0);
4.2168 + if (ch >= 0) {
4.2169 + append(ch, first);
4.2170 + first++;
4.2171 + if (isSupplementary(ch)) {
4.2172 + hasSupplementary = true;
4.2173 + }
4.2174 + ch = peek();
4.2175 + continue;
4.2176 + } else if (first == 0) {
4.2177 + return root;
4.2178 + }
4.2179 + // Unwind meta escape sequence
4.2180 + cursor = prev;
4.2181 + break;
4.2182 + case 0:
4.2183 + if (cursor >= patternLength) {
4.2184 + break;
4.2185 + }
4.2186 + // Fall through
4.2187 + default:
4.2188 + prev = cursor;
4.2189 + append(ch, first);
4.2190 + first++;
4.2191 + if (isSupplementary(ch)) {
4.2192 + hasSupplementary = true;
4.2193 + }
4.2194 + ch = next();
4.2195 + continue;
4.2196 + }
4.2197 + break;
4.2198 + }
4.2199 + if (first == 1) {
4.2200 + return newSingle(buffer[0]);
4.2201 + } else {
4.2202 + return newSlice(buffer, first, hasSupplementary);
4.2203 + }
4.2204 + }
4.2205 +
4.2206 + private void append(int ch, int len) {
4.2207 + if (len >= buffer.length) {
4.2208 + int[] tmp = new int[len+len];
4.2209 + System.arraycopy(buffer, 0, tmp, 0, len);
4.2210 + buffer = tmp;
4.2211 + }
4.2212 + buffer[len] = ch;
4.2213 + }
4.2214 +
4.2215 + /**
4.2216 + * Parses a backref greedily, taking as many numbers as it
4.2217 + * can. The first digit is always treated as a backref, but
4.2218 + * multi digit numbers are only treated as a backref if at
4.2219 + * least that many backrefs exist at this point in the regex.
4.2220 + */
4.2221 + private Node ref(int refNum) {
4.2222 + boolean done = false;
4.2223 + while(!done) {
4.2224 + int ch = peek();
4.2225 + switch(ch) {
4.2226 + case '0':
4.2227 + case '1':
4.2228 + case '2':
4.2229 + case '3':
4.2230 + case '4':
4.2231 + case '5':
4.2232 + case '6':
4.2233 + case '7':
4.2234 + case '8':
4.2235 + case '9':
4.2236 + int newRefNum = (refNum * 10) + (ch - '0');
4.2237 + // Add another number if it doesn't make a group
4.2238 + // that doesn't exist
4.2239 + if (capturingGroupCount - 1 < newRefNum) {
4.2240 + done = true;
4.2241 + break;
4.2242 + }
4.2243 + refNum = newRefNum;
4.2244 + read();
4.2245 + break;
4.2246 + default:
4.2247 + done = true;
4.2248 + break;
4.2249 + }
4.2250 + }
4.2251 + if (has(CASE_INSENSITIVE))
4.2252 + return new CIBackRef(refNum, has(UNICODE_CASE));
4.2253 + else
4.2254 + return new BackRef(refNum);
4.2255 + }
4.2256 +
4.2257 + /**
4.2258 + * Parses an escape sequence to determine the actual value that needs
4.2259 + * to be matched.
4.2260 + * If -1 is returned and create was true a new object was added to the tree
4.2261 + * to handle the escape sequence.
4.2262 + * If the returned value is greater than zero, it is the value that
4.2263 + * matches the escape sequence.
4.2264 + */
4.2265 + private int escape(boolean inclass, boolean create) {
4.2266 + int ch = skip();
4.2267 + switch (ch) {
4.2268 + case '0':
4.2269 + return o();
4.2270 + case '1':
4.2271 + case '2':
4.2272 + case '3':
4.2273 + case '4':
4.2274 + case '5':
4.2275 + case '6':
4.2276 + case '7':
4.2277 + case '8':
4.2278 + case '9':
4.2279 + if (inclass) break;
4.2280 + if (create) {
4.2281 + root = ref((ch - '0'));
4.2282 + }
4.2283 + return -1;
4.2284 + case 'A':
4.2285 + if (inclass) break;
4.2286 + if (create) root = new Begin();
4.2287 + return -1;
4.2288 + case 'B':
4.2289 + if (inclass) break;
4.2290 + if (create) root = new Bound(Bound.NONE, has(UNICODE_CHARACTER_CLASS));
4.2291 + return -1;
4.2292 + case 'C':
4.2293 + break;
4.2294 + case 'D':
4.2295 + if (create) root = has(UNICODE_CHARACTER_CLASS)
4.2296 + ? new Utype(UnicodeProp.DIGIT).complement()
4.2297 + : new Ctype(ASCII.DIGIT).complement();
4.2298 + return -1;
4.2299 + case 'E':
4.2300 + case 'F':
4.2301 + break;
4.2302 + case 'G':
4.2303 + if (inclass) break;
4.2304 + if (create) root = new LastMatch();
4.2305 + return -1;
4.2306 + case 'H':
4.2307 + case 'I':
4.2308 + case 'J':
4.2309 + case 'K':
4.2310 + case 'L':
4.2311 + case 'M':
4.2312 + case 'N':
4.2313 + case 'O':
4.2314 + case 'P':
4.2315 + case 'Q':
4.2316 + case 'R':
4.2317 + break;
4.2318 + case 'S':
4.2319 + if (create) root = has(UNICODE_CHARACTER_CLASS)
4.2320 + ? new Utype(UnicodeProp.WHITE_SPACE).complement()
4.2321 + : new Ctype(ASCII.SPACE).complement();
4.2322 + return -1;
4.2323 + case 'T':
4.2324 + case 'U':
4.2325 + case 'V':
4.2326 + break;
4.2327 + case 'W':
4.2328 + if (create) root = has(UNICODE_CHARACTER_CLASS)
4.2329 + ? new Utype(UnicodeProp.WORD).complement()
4.2330 + : new Ctype(ASCII.WORD).complement();
4.2331 + return -1;
4.2332 + case 'X':
4.2333 + case 'Y':
4.2334 + break;
4.2335 + case 'Z':
4.2336 + if (inclass) break;
4.2337 + if (create) {
4.2338 + if (has(UNIX_LINES))
4.2339 + root = new UnixDollar(false);
4.2340 + else
4.2341 + root = new Dollar(false);
4.2342 + }
4.2343 + return -1;
4.2344 + case 'a':
4.2345 + return '\007';
4.2346 + case 'b':
4.2347 + if (inclass) break;
4.2348 + if (create) root = new Bound(Bound.BOTH, has(UNICODE_CHARACTER_CLASS));
4.2349 + return -1;
4.2350 + case 'c':
4.2351 + return c();
4.2352 + case 'd':
4.2353 + if (create) root = has(UNICODE_CHARACTER_CLASS)
4.2354 + ? new Utype(UnicodeProp.DIGIT)
4.2355 + : new Ctype(ASCII.DIGIT);
4.2356 + return -1;
4.2357 + case 'e':
4.2358 + return '\033';
4.2359 + case 'f':
4.2360 + return '\f';
4.2361 + case 'g':
4.2362 + case 'h':
4.2363 + case 'i':
4.2364 + case 'j':
4.2365 + break;
4.2366 + case 'k':
4.2367 + if (inclass)
4.2368 + break;
4.2369 + if (read() != '<')
4.2370 + throw error("\\k is not followed by '<' for named capturing group");
4.2371 + String name = groupname(read());
4.2372 + if (!namedGroups().containsKey(name))
4.2373 + throw error("(named capturing group <"+ name+"> does not exit");
4.2374 + if (create) {
4.2375 + if (has(CASE_INSENSITIVE))
4.2376 + root = new CIBackRef(namedGroups().get(name), has(UNICODE_CASE));
4.2377 + else
4.2378 + root = new BackRef(namedGroups().get(name));
4.2379 + }
4.2380 + return -1;
4.2381 + case 'l':
4.2382 + case 'm':
4.2383 + break;
4.2384 + case 'n':
4.2385 + return '\n';
4.2386 + case 'o':
4.2387 + case 'p':
4.2388 + case 'q':
4.2389 + break;
4.2390 + case 'r':
4.2391 + return '\r';
4.2392 + case 's':
4.2393 + if (create) root = has(UNICODE_CHARACTER_CLASS)
4.2394 + ? new Utype(UnicodeProp.WHITE_SPACE)
4.2395 + : new Ctype(ASCII.SPACE);
4.2396 + return -1;
4.2397 + case 't':
4.2398 + return '\t';
4.2399 + case 'u':
4.2400 + return u();
4.2401 + case 'v':
4.2402 + return '\013';
4.2403 + case 'w':
4.2404 + if (create) root = has(UNICODE_CHARACTER_CLASS)
4.2405 + ? new Utype(UnicodeProp.WORD)
4.2406 + : new Ctype(ASCII.WORD);
4.2407 + return -1;
4.2408 + case 'x':
4.2409 + return x();
4.2410 + case 'y':
4.2411 + break;
4.2412 + case 'z':
4.2413 + if (inclass) break;
4.2414 + if (create) root = new End();
4.2415 + return -1;
4.2416 + default:
4.2417 + return ch;
4.2418 + }
4.2419 + throw error("Illegal/unsupported escape sequence");
4.2420 + }
4.2421 +
4.2422 + /**
4.2423 + * Parse a character class, and return the node that matches it.
4.2424 + *
4.2425 + * Consumes a ] on the way out if consume is true. Usually consume
4.2426 + * is true except for the case of [abc&&def] where def is a separate
4.2427 + * right hand node with "understood" brackets.
4.2428 + */
4.2429 + private CharProperty clazz(boolean consume) {
4.2430 + CharProperty prev = null;
4.2431 + CharProperty node = null;
4.2432 + BitClass bits = new BitClass();
4.2433 + boolean include = true;
4.2434 + boolean firstInClass = true;
4.2435 + int ch = next();
4.2436 + for (;;) {
4.2437 + switch (ch) {
4.2438 + case '^':
4.2439 + // Negates if first char in a class, otherwise literal
4.2440 + if (firstInClass) {
4.2441 + if (temp[cursor-1] != '[')
4.2442 + break;
4.2443 + ch = next();
4.2444 + include = !include;
4.2445 + continue;
4.2446 + } else {
4.2447 + // ^ not first in class, treat as literal
4.2448 + break;
4.2449 + }
4.2450 + case '[':
4.2451 + firstInClass = false;
4.2452 + node = clazz(true);
4.2453 + if (prev == null)
4.2454 + prev = node;
4.2455 + else
4.2456 + prev = union(prev, node);
4.2457 + ch = peek();
4.2458 + continue;
4.2459 + case '&':
4.2460 + firstInClass = false;
4.2461 + ch = next();
4.2462 + if (ch == '&') {
4.2463 + ch = next();
4.2464 + CharProperty rightNode = null;
4.2465 + while (ch != ']' && ch != '&') {
4.2466 + if (ch == '[') {
4.2467 + if (rightNode == null)
4.2468 + rightNode = clazz(true);
4.2469 + else
4.2470 + rightNode = union(rightNode, clazz(true));
4.2471 + } else { // abc&&def
4.2472 + unread();
4.2473 + rightNode = clazz(false);
4.2474 + }
4.2475 + ch = peek();
4.2476 + }
4.2477 + if (rightNode != null)
4.2478 + node = rightNode;
4.2479 + if (prev == null) {
4.2480 + if (rightNode == null)
4.2481 + throw error("Bad class syntax");
4.2482 + else
4.2483 + prev = rightNode;
4.2484 + } else {
4.2485 + prev = intersection(prev, node);
4.2486 + }
4.2487 + } else {
4.2488 + // treat as a literal &
4.2489 + unread();
4.2490 + break;
4.2491 + }
4.2492 + continue;
4.2493 + case 0:
4.2494 + firstInClass = false;
4.2495 + if (cursor >= patternLength)
4.2496 + throw error("Unclosed character class");
4.2497 + break;
4.2498 + case ']':
4.2499 + firstInClass = false;
4.2500 + if (prev != null) {
4.2501 + if (consume)
4.2502 + next();
4.2503 + return prev;
4.2504 + }
4.2505 + break;
4.2506 + default:
4.2507 + firstInClass = false;
4.2508 + break;
4.2509 + }
4.2510 + node = range(bits);
4.2511 + if (include) {
4.2512 + if (prev == null) {
4.2513 + prev = node;
4.2514 + } else {
4.2515 + if (prev != node)
4.2516 + prev = union(prev, node);
4.2517 + }
4.2518 + } else {
4.2519 + if (prev == null) {
4.2520 + prev = node.complement();
4.2521 + } else {
4.2522 + if (prev != node)
4.2523 + prev = setDifference(prev, node);
4.2524 + }
4.2525 + }
4.2526 + ch = peek();
4.2527 + }
4.2528 + }
4.2529 +
4.2530 + private CharProperty bitsOrSingle(BitClass bits, int ch) {
4.2531 + /* Bits can only handle codepoints in [u+0000-u+00ff] range.
4.2532 + Use "single" node instead of bits when dealing with unicode
4.2533 + case folding for codepoints listed below.
4.2534 + (1)Uppercase out of range: u+00ff, u+00b5
4.2535 + toUpperCase(u+00ff) -> u+0178
4.2536 + toUpperCase(u+00b5) -> u+039c
4.2537 + (2)LatinSmallLetterLongS u+17f
4.2538 + toUpperCase(u+017f) -> u+0053
4.2539 + (3)LatinSmallLetterDotlessI u+131
4.2540 + toUpperCase(u+0131) -> u+0049
4.2541 + (4)LatinCapitalLetterIWithDotAbove u+0130
4.2542 + toLowerCase(u+0130) -> u+0069
4.2543 + (5)KelvinSign u+212a
4.2544 + toLowerCase(u+212a) ==> u+006B
4.2545 + (6)AngstromSign u+212b
4.2546 + toLowerCase(u+212b) ==> u+00e5
4.2547 + */
4.2548 + int d;
4.2549 + if (ch < 256 &&
4.2550 + !(has(CASE_INSENSITIVE) && has(UNICODE_CASE) &&
4.2551 + (ch == 0xff || ch == 0xb5 ||
4.2552 + ch == 0x49 || ch == 0x69 || //I and i
4.2553 + ch == 0x53 || ch == 0x73 || //S and s
4.2554 + ch == 0x4b || ch == 0x6b || //K and k
4.2555 + ch == 0xc5 || ch == 0xe5))) //A+ring
4.2556 + return bits.add(ch, flags());
4.2557 + return newSingle(ch);
4.2558 + }
4.2559 +
4.2560 + /**
4.2561 + * Parse a single character or a character range in a character class
4.2562 + * and return its representative node.
4.2563 + */
4.2564 + private CharProperty range(BitClass bits) {
4.2565 + int ch = peek();
4.2566 + if (ch == '\\') {
4.2567 + ch = nextEscaped();
4.2568 + if (ch == 'p' || ch == 'P') { // A property
4.2569 + boolean comp = (ch == 'P');
4.2570 + boolean oneLetter = true;
4.2571 + // Consume { if present
4.2572 + ch = next();
4.2573 + if (ch != '{')
4.2574 + unread();
4.2575 + else
4.2576 + oneLetter = false;
4.2577 + return family(oneLetter, comp);
4.2578 + } else { // ordinary escape
4.2579 + unread();
4.2580 + ch = escape(true, true);
4.2581 + if (ch == -1)
4.2582 + return (CharProperty) root;
4.2583 + }
4.2584 + } else {
4.2585 + ch = single();
4.2586 + }
4.2587 + if (ch >= 0) {
4.2588 + if (peek() == '-') {
4.2589 + int endRange = temp[cursor+1];
4.2590 + if (endRange == '[') {
4.2591 + return bitsOrSingle(bits, ch);
4.2592 + }
4.2593 + if (endRange != ']') {
4.2594 + next();
4.2595 + int m = single();
4.2596 + if (m < ch)
4.2597 + throw error("Illegal character range");
4.2598 + if (has(CASE_INSENSITIVE))
4.2599 + return caseInsensitiveRangeFor(ch, m);
4.2600 + else
4.2601 + return rangeFor(ch, m);
4.2602 + }
4.2603 + }
4.2604 + return bitsOrSingle(bits, ch);
4.2605 + }
4.2606 + throw error("Unexpected character '"+((char)ch)+"'");
4.2607 + }
4.2608 +
4.2609 + private int single() {
4.2610 + int ch = peek();
4.2611 + switch (ch) {
4.2612 + case '\\':
4.2613 + return escape(true, false);
4.2614 + default:
4.2615 + next();
4.2616 + return ch;
4.2617 + }
4.2618 + }
4.2619 +
4.2620 + /**
4.2621 + * Parses a Unicode character family and returns its representative node.
4.2622 + */
4.2623 + private CharProperty family(boolean singleLetter,
4.2624 + boolean maybeComplement)
4.2625 + {
4.2626 + next();
4.2627 + String name;
4.2628 + CharProperty node = null;
4.2629 +
4.2630 + if (singleLetter) {
4.2631 + int c = temp[cursor];
4.2632 + if (!Character.isSupplementaryCodePoint(c)) {
4.2633 + name = String.valueOf((char)c);
4.2634 + } else {
4.2635 + name = new String(temp, cursor, 1);
4.2636 + }
4.2637 + read();
4.2638 + } else {
4.2639 + int i = cursor;
4.2640 + mark('}');
4.2641 + while(read() != '}') {
4.2642 + }
4.2643 + mark('\000');
4.2644 + int j = cursor;
4.2645 + if (j > patternLength)
4.2646 + throw error("Unclosed character family");
4.2647 + if (i + 1 >= j)
4.2648 + throw error("Empty character family");
4.2649 + name = new String(temp, i, j-i-1);
4.2650 + }
4.2651 +
4.2652 + int i = name.indexOf('=');
4.2653 + if (i != -1) {
4.2654 + // property construct \p{name=value}
4.2655 + String value = name.substring(i + 1);
4.2656 + name = name.substring(0, i).toLowerCase(Locale.ENGLISH);
4.2657 + if ("sc".equals(name) || "script".equals(name)) {
4.2658 + node = unicodeScriptPropertyFor(value);
4.2659 + } else if ("blk".equals(name) || "block".equals(name)) {
4.2660 + node = unicodeBlockPropertyFor(value);
4.2661 + } else if ("gc".equals(name) || "general_category".equals(name)) {
4.2662 + node = charPropertyNodeFor(value);
4.2663 + } else {
4.2664 + throw error("Unknown Unicode property {name=<" + name + ">, "
4.2665 + + "value=<" + value + ">}");
4.2666 + }
4.2667 + } else {
4.2668 + if (name.startsWith("In")) {
4.2669 + // \p{inBlockName}
4.2670 + node = unicodeBlockPropertyFor(name.substring(2));
4.2671 + } else if (name.startsWith("Is")) {
4.2672 + // \p{isGeneralCategory} and \p{isScriptName}
4.2673 + name = name.substring(2);
4.2674 + UnicodeProp uprop = UnicodeProp.forName(name);
4.2675 + if (uprop != null)
4.2676 + node = new Utype(uprop);
4.2677 + if (node == null)
4.2678 + node = CharPropertyNames.charPropertyFor(name);
4.2679 + if (node == null)
4.2680 + node = unicodeScriptPropertyFor(name);
4.2681 + } else {
4.2682 + if (has(UNICODE_CHARACTER_CLASS)) {
4.2683 + UnicodeProp uprop = UnicodeProp.forPOSIXName(name);
4.2684 + if (uprop != null)
4.2685 + node = new Utype(uprop);
4.2686 + }
4.2687 + if (node == null)
4.2688 + node = charPropertyNodeFor(name);
4.2689 + }
4.2690 + }
4.2691 + if (maybeComplement) {
4.2692 + if (node instanceof Category || node instanceof Block)
4.2693 + hasSupplementary = true;
4.2694 + node = node.complement();
4.2695 + }
4.2696 + return node;
4.2697 + }
4.2698 +
4.2699 +
4.2700 + /**
4.2701 + * Returns a CharProperty matching all characters belong to
4.2702 + * a UnicodeScript.
4.2703 + */
4.2704 + private CharProperty unicodeScriptPropertyFor(String name) {
4.2705 + final Character.UnicodeScript script;
4.2706 + try {
4.2707 + script = Character.UnicodeScript.forName(name);
4.2708 + } catch (IllegalArgumentException iae) {
4.2709 + throw error("Unknown character script name {" + name + "}");
4.2710 + }
4.2711 + return new Script(script);
4.2712 + }
4.2713 +
4.2714 + /**
4.2715 + * Returns a CharProperty matching all characters in a UnicodeBlock.
4.2716 + */
4.2717 + private CharProperty unicodeBlockPropertyFor(String name) {
4.2718 + final Character.UnicodeBlock block;
4.2719 + try {
4.2720 + block = Character.UnicodeBlock.forName(name);
4.2721 + } catch (IllegalArgumentException iae) {
4.2722 + throw error("Unknown character block name {" + name + "}");
4.2723 + }
4.2724 + return new Block(block);
4.2725 + }
4.2726 +
4.2727 + /**
4.2728 + * Returns a CharProperty matching all characters in a named property.
4.2729 + */
4.2730 + private CharProperty charPropertyNodeFor(String name) {
4.2731 + CharProperty p = CharPropertyNames.charPropertyFor(name);
4.2732 + if (p == null)
4.2733 + throw error("Unknown character property name {" + name + "}");
4.2734 + return p;
4.2735 + }
4.2736 +
4.2737 + /**
4.2738 + * Parses and returns the name of a "named capturing group", the trailing
4.2739 + * ">" is consumed after parsing.
4.2740 + */
4.2741 + private String groupname(int ch) {
4.2742 + StringBuilder sb = new StringBuilder();
4.2743 + sb.append(Character.toChars(ch));
4.2744 + while (ASCII.isLower(ch=read()) || ASCII.isUpper(ch) ||
4.2745 + ASCII.isDigit(ch)) {
4.2746 + sb.append(Character.toChars(ch));
4.2747 + }
4.2748 + if (sb.length() == 0)
4.2749 + throw error("named capturing group has 0 length name");
4.2750 + if (ch != '>')
4.2751 + throw error("named capturing group is missing trailing '>'");
4.2752 + return sb.toString();
4.2753 + }
4.2754 +
4.2755 + /**
4.2756 + * Parses a group and returns the head node of a set of nodes that process
4.2757 + * the group. Sometimes a double return system is used where the tail is
4.2758 + * returned in root.
4.2759 + */
4.2760 + private Node group0() {
4.2761 + boolean capturingGroup = false;
4.2762 + Node head = null;
4.2763 + Node tail = null;
4.2764 + int save = flags;
4.2765 + root = null;
4.2766 + int ch = next();
4.2767 + if (ch == '?') {
4.2768 + ch = skip();
4.2769 + switch (ch) {
4.2770 + case ':': // (?:xxx) pure group
4.2771 + head = createGroup(true);
4.2772 + tail = root;
4.2773 + head.next = expr(tail);
4.2774 + break;
4.2775 + case '=': // (?=xxx) and (?!xxx) lookahead
4.2776 + case '!':
4.2777 + head = createGroup(true);
4.2778 + tail = root;
4.2779 + head.next = expr(tail);
4.2780 + if (ch == '=') {
4.2781 + head = tail = new Pos(head);
4.2782 + } else {
4.2783 + head = tail = new Neg(head);
4.2784 + }
4.2785 + break;
4.2786 + case '>': // (?>xxx) independent group
4.2787 + head = createGroup(true);
4.2788 + tail = root;
4.2789 + head.next = expr(tail);
4.2790 + head = tail = new Ques(head, INDEPENDENT);
4.2791 + break;
4.2792 + case '<': // (?<xxx) look behind
4.2793 + ch = read();
4.2794 + if (ASCII.isLower(ch) || ASCII.isUpper(ch)) {
4.2795 + // named captured group
4.2796 + String name = groupname(ch);
4.2797 + if (namedGroups().containsKey(name))
4.2798 + throw error("Named capturing group <" + name
4.2799 + + "> is already defined");
4.2800 + capturingGroup = true;
4.2801 + head = createGroup(false);
4.2802 + tail = root;
4.2803 + namedGroups().put(name, capturingGroupCount-1);
4.2804 + head.next = expr(tail);
4.2805 + break;
4.2806 + }
4.2807 + int start = cursor;
4.2808 + head = createGroup(true);
4.2809 + tail = root;
4.2810 + head.next = expr(tail);
4.2811 + tail.next = lookbehindEnd;
4.2812 + TreeInfo info = new TreeInfo();
4.2813 + head.study(info);
4.2814 + if (info.maxValid == false) {
4.2815 + throw error("Look-behind group does not have "
4.2816 + + "an obvious maximum length");
4.2817 + }
4.2818 + boolean hasSupplementary = findSupplementary(start, patternLength);
4.2819 + if (ch == '=') {
4.2820 + head = tail = (hasSupplementary ?
4.2821 + new BehindS(head, info.maxLength,
4.2822 + info.minLength) :
4.2823 + new Behind(head, info.maxLength,
4.2824 + info.minLength));
4.2825 + } else if (ch == '!') {
4.2826 + head = tail = (hasSupplementary ?
4.2827 + new NotBehindS(head, info.maxLength,
4.2828 + info.minLength) :
4.2829 + new NotBehind(head, info.maxLength,
4.2830 + info.minLength));
4.2831 + } else {
4.2832 + throw error("Unknown look-behind group");
4.2833 + }
4.2834 + break;
4.2835 + case '$':
4.2836 + case '@':
4.2837 + throw error("Unknown group type");
4.2838 + default: // (?xxx:) inlined match flags
4.2839 + unread();
4.2840 + addFlag();
4.2841 + ch = read();
4.2842 + if (ch == ')') {
4.2843 + return null; // Inline modifier only
4.2844 + }
4.2845 + if (ch != ':') {
4.2846 + throw error("Unknown inline modifier");
4.2847 + }
4.2848 + head = createGroup(true);
4.2849 + tail = root;
4.2850 + head.next = expr(tail);
4.2851 + break;
4.2852 + }
4.2853 + } else { // (xxx) a regular group
4.2854 + capturingGroup = true;
4.2855 + head = createGroup(false);
4.2856 + tail = root;
4.2857 + head.next = expr(tail);
4.2858 + }
4.2859 +
4.2860 + accept(')', "Unclosed group");
4.2861 + flags = save;
4.2862 +
4.2863 + // Check for quantifiers
4.2864 + Node node = closure(head);
4.2865 + if (node == head) { // No closure
4.2866 + root = tail;
4.2867 + return node; // Dual return
4.2868 + }
4.2869 + if (head == tail) { // Zero length assertion
4.2870 + root = node;
4.2871 + return node; // Dual return
4.2872 + }
4.2873 +
4.2874 + if (node instanceof Ques) {
4.2875 + Ques ques = (Ques) node;
4.2876 + if (ques.type == POSSESSIVE) {
4.2877 + root = node;
4.2878 + return node;
4.2879 + }
4.2880 + tail.next = new BranchConn();
4.2881 + tail = tail.next;
4.2882 + if (ques.type == GREEDY) {
4.2883 + head = new Branch(head, null, tail);
4.2884 + } else { // Reluctant quantifier
4.2885 + head = new Branch(null, head, tail);
4.2886 + }
4.2887 + root = tail;
4.2888 + return head;
4.2889 + } else if (node instanceof Curly) {
4.2890 + Curly curly = (Curly) node;
4.2891 + if (curly.type == POSSESSIVE) {
4.2892 + root = node;
4.2893 + return node;
4.2894 + }
4.2895 + // Discover if the group is deterministic
4.2896 + TreeInfo info = new TreeInfo();
4.2897 + if (head.study(info)) { // Deterministic
4.2898 + GroupTail temp = (GroupTail) tail;
4.2899 + head = root = new GroupCurly(head.next, curly.cmin,
4.2900 + curly.cmax, curly.type,
4.2901 + ((GroupTail)tail).localIndex,
4.2902 + ((GroupTail)tail).groupIndex,
4.2903 + capturingGroup);
4.2904 + return head;
4.2905 + } else { // Non-deterministic
4.2906 + int temp = ((GroupHead) head).localIndex;
4.2907 + Loop loop;
4.2908 + if (curly.type == GREEDY)
4.2909 + loop = new Loop(this.localCount, temp);
4.2910 + else // Reluctant Curly
4.2911 + loop = new LazyLoop(this.localCount, temp);
4.2912 + Prolog prolog = new Prolog(loop);
4.2913 + this.localCount += 1;
4.2914 + loop.cmin = curly.cmin;
4.2915 + loop.cmax = curly.cmax;
4.2916 + loop.body = head;
4.2917 + tail.next = loop;
4.2918 + root = loop;
4.2919 + return prolog; // Dual return
4.2920 + }
4.2921 + }
4.2922 + throw error("Internal logic error");
4.2923 + }
4.2924 +
4.2925 + /**
4.2926 + * Create group head and tail nodes using double return. If the group is
4.2927 + * created with anonymous true then it is a pure group and should not
4.2928 + * affect group counting.
4.2929 + */
4.2930 + private Node createGroup(boolean anonymous) {
4.2931 + int localIndex = localCount++;
4.2932 + int groupIndex = 0;
4.2933 + if (!anonymous)
4.2934 + groupIndex = capturingGroupCount++;
4.2935 + GroupHead head = new GroupHead(localIndex);
4.2936 + root = new GroupTail(localIndex, groupIndex);
4.2937 + if (!anonymous && groupIndex < 10)
4.2938 + groupNodes[groupIndex] = head;
4.2939 + return head;
4.2940 + }
4.2941 +
4.2942 + /**
4.2943 + * Parses inlined match flags and set them appropriately.
4.2944 + */
4.2945 + private void addFlag() {
4.2946 + int ch = peek();
4.2947 + for (;;) {
4.2948 + switch (ch) {
4.2949 + case 'i':
4.2950 + flags |= CASE_INSENSITIVE;
4.2951 + break;
4.2952 + case 'm':
4.2953 + flags |= MULTILINE;
4.2954 + break;
4.2955 + case 's':
4.2956 + flags |= DOTALL;
4.2957 + break;
4.2958 + case 'd':
4.2959 + flags |= UNIX_LINES;
4.2960 + break;
4.2961 + case 'u':
4.2962 + flags |= UNICODE_CASE;
4.2963 + break;
4.2964 + case 'c':
4.2965 + flags |= CANON_EQ;
4.2966 + break;
4.2967 + case 'x':
4.2968 + flags |= COMMENTS;
4.2969 + break;
4.2970 + case 'U':
4.2971 + flags |= (UNICODE_CHARACTER_CLASS | UNICODE_CASE);
4.2972 + break;
4.2973 + case '-': // subFlag then fall through
4.2974 + ch = next();
4.2975 + subFlag();
4.2976 + default:
4.2977 + return;
4.2978 + }
4.2979 + ch = next();
4.2980 + }
4.2981 + }
4.2982 +
4.2983 + /**
4.2984 + * Parses the second part of inlined match flags and turns off
4.2985 + * flags appropriately.
4.2986 + */
4.2987 + private void subFlag() {
4.2988 + int ch = peek();
4.2989 + for (;;) {
4.2990 + switch (ch) {
4.2991 + case 'i':
4.2992 + flags &= ~CASE_INSENSITIVE;
4.2993 + break;
4.2994 + case 'm':
4.2995 + flags &= ~MULTILINE;
4.2996 + break;
4.2997 + case 's':
4.2998 + flags &= ~DOTALL;
4.2999 + break;
4.3000 + case 'd':
4.3001 + flags &= ~UNIX_LINES;
4.3002 + break;
4.3003 + case 'u':
4.3004 + flags &= ~UNICODE_CASE;
4.3005 + break;
4.3006 + case 'c':
4.3007 + flags &= ~CANON_EQ;
4.3008 + break;
4.3009 + case 'x':
4.3010 + flags &= ~COMMENTS;
4.3011 + break;
4.3012 + case 'U':
4.3013 + flags &= ~(UNICODE_CHARACTER_CLASS | UNICODE_CASE);
4.3014 + default:
4.3015 + return;
4.3016 + }
4.3017 + ch = next();
4.3018 + }
4.3019 + }
4.3020 +
4.3021 + static final int MAX_REPS = 0x7FFFFFFF;
4.3022 +
4.3023 + static final int GREEDY = 0;
4.3024 +
4.3025 + static final int LAZY = 1;
4.3026 +
4.3027 + static final int POSSESSIVE = 2;
4.3028 +
4.3029 + static final int INDEPENDENT = 3;
4.3030 +
4.3031 + /**
4.3032 + * Processes repetition. If the next character peeked is a quantifier
4.3033 + * then new nodes must be appended to handle the repetition.
4.3034 + * Prev could be a single or a group, so it could be a chain of nodes.
4.3035 + */
4.3036 + private Node closure(Node prev) {
4.3037 + Node atom;
4.3038 + int ch = peek();
4.3039 + switch (ch) {
4.3040 + case '?':
4.3041 + ch = next();
4.3042 + if (ch == '?') {
4.3043 + next();
4.3044 + return new Ques(prev, LAZY);
4.3045 + } else if (ch == '+') {
4.3046 + next();
4.3047 + return new Ques(prev, POSSESSIVE);
4.3048 + }
4.3049 + return new Ques(prev, GREEDY);
4.3050 + case '*':
4.3051 + ch = next();
4.3052 + if (ch == '?') {
4.3053 + next();
4.3054 + return new Curly(prev, 0, MAX_REPS, LAZY);
4.3055 + } else if (ch == '+') {
4.3056 + next();
4.3057 + return new Curly(prev, 0, MAX_REPS, POSSESSIVE);
4.3058 + }
4.3059 + return new Curly(prev, 0, MAX_REPS, GREEDY);
4.3060 + case '+':
4.3061 + ch = next();
4.3062 + if (ch == '?') {
4.3063 + next();
4.3064 + return new Curly(prev, 1, MAX_REPS, LAZY);
4.3065 + } else if (ch == '+') {
4.3066 + next();
4.3067 + return new Curly(prev, 1, MAX_REPS, POSSESSIVE);
4.3068 + }
4.3069 + return new Curly(prev, 1, MAX_REPS, GREEDY);
4.3070 + case '{':
4.3071 + ch = temp[cursor+1];
4.3072 + if (ASCII.isDigit(ch)) {
4.3073 + skip();
4.3074 + int cmin = 0;
4.3075 + do {
4.3076 + cmin = cmin * 10 + (ch - '0');
4.3077 + } while (ASCII.isDigit(ch = read()));
4.3078 + int cmax = cmin;
4.3079 + if (ch == ',') {
4.3080 + ch = read();
4.3081 + cmax = MAX_REPS;
4.3082 + if (ch != '}') {
4.3083 + cmax = 0;
4.3084 + while (ASCII.isDigit(ch)) {
4.3085 + cmax = cmax * 10 + (ch - '0');
4.3086 + ch = read();
4.3087 + }
4.3088 + }
4.3089 + }
4.3090 + if (ch != '}')
4.3091 + throw error("Unclosed counted closure");
4.3092 + if (((cmin) | (cmax) | (cmax - cmin)) < 0)
4.3093 + throw error("Illegal repetition range");
4.3094 + Curly curly;
4.3095 + ch = peek();
4.3096 + if (ch == '?') {
4.3097 + next();
4.3098 + curly = new Curly(prev, cmin, cmax, LAZY);
4.3099 + } else if (ch == '+') {
4.3100 + next();
4.3101 + curly = new Curly(prev, cmin, cmax, POSSESSIVE);
4.3102 + } else {
4.3103 + curly = new Curly(prev, cmin, cmax, GREEDY);
4.3104 + }
4.3105 + return curly;
4.3106 + } else {
4.3107 + throw error("Illegal repetition");
4.3108 + }
4.3109 + default:
4.3110 + return prev;
4.3111 + }
4.3112 + }
4.3113 +
4.3114 + /**
4.3115 + * Utility method for parsing control escape sequences.
4.3116 + */
4.3117 + private int c() {
4.3118 + if (cursor < patternLength) {
4.3119 + return read() ^ 64;
4.3120 + }
4.3121 + throw error("Illegal control escape sequence");
4.3122 + }
4.3123 +
4.3124 + /**
4.3125 + * Utility method for parsing octal escape sequences.
4.3126 + */
4.3127 + private int o() {
4.3128 + int n = read();
4.3129 + if (((n-'0')|('7'-n)) >= 0) {
4.3130 + int m = read();
4.3131 + if (((m-'0')|('7'-m)) >= 0) {
4.3132 + int o = read();
4.3133 + if ((((o-'0')|('7'-o)) >= 0) && (((n-'0')|('3'-n)) >= 0)) {
4.3134 + return (n - '0') * 64 + (m - '0') * 8 + (o - '0');
4.3135 + }
4.3136 + unread();
4.3137 + return (n - '0') * 8 + (m - '0');
4.3138 + }
4.3139 + unread();
4.3140 + return (n - '0');
4.3141 + }
4.3142 + throw error("Illegal octal escape sequence");
4.3143 + }
4.3144 +
4.3145 + /**
4.3146 + * Utility method for parsing hexadecimal escape sequences.
4.3147 + */
4.3148 + private int x() {
4.3149 + int n = read();
4.3150 + if (ASCII.isHexDigit(n)) {
4.3151 + int m = read();
4.3152 + if (ASCII.isHexDigit(m)) {
4.3153 + return ASCII.toDigit(n) * 16 + ASCII.toDigit(m);
4.3154 + }
4.3155 + } else if (n == '{' && ASCII.isHexDigit(peek())) {
4.3156 + int ch = 0;
4.3157 + while (ASCII.isHexDigit(n = read())) {
4.3158 + ch = (ch << 4) + ASCII.toDigit(n);
4.3159 + if (ch > Character.MAX_CODE_POINT)
4.3160 + throw error("Hexadecimal codepoint is too big");
4.3161 + }
4.3162 + if (n != '}')
4.3163 + throw error("Unclosed hexadecimal escape sequence");
4.3164 + return ch;
4.3165 + }
4.3166 + throw error("Illegal hexadecimal escape sequence");
4.3167 + }
4.3168 +
4.3169 + /**
4.3170 + * Utility method for parsing unicode escape sequences.
4.3171 + */
4.3172 + private int cursor() {
4.3173 + return cursor;
4.3174 + }
4.3175 +
4.3176 + private void setcursor(int pos) {
4.3177 + cursor = pos;
4.3178 + }
4.3179 +
4.3180 + private int uxxxx() {
4.3181 + int n = 0;
4.3182 + for (int i = 0; i < 4; i++) {
4.3183 + int ch = read();
4.3184 + if (!ASCII.isHexDigit(ch)) {
4.3185 + throw error("Illegal Unicode escape sequence");
4.3186 + }
4.3187 + n = n * 16 + ASCII.toDigit(ch);
4.3188 + }
4.3189 + return n;
4.3190 + }
4.3191 +
4.3192 + private int u() {
4.3193 + int n = uxxxx();
4.3194 + if (Character.isHighSurrogate((char)n)) {
4.3195 + int cur = cursor();
4.3196 + if (read() == '\\' && read() == 'u') {
4.3197 + int n2 = uxxxx();
4.3198 + if (Character.isLowSurrogate((char)n2))
4.3199 + return Character.toCodePoint((char)n, (char)n2);
4.3200 + }
4.3201 + setcursor(cur);
4.3202 + }
4.3203 + return n;
4.3204 + }
4.3205 +
4.3206 + //
4.3207 + // Utility methods for code point support
4.3208 + //
4.3209 +
4.3210 + private static final int countChars(CharSequence seq, int index,
4.3211 + int lengthInCodePoints) {
4.3212 + // optimization
4.3213 + if (lengthInCodePoints == 1 && !Character.isHighSurrogate(seq.charAt(index))) {
4.3214 + assert (index >= 0 && index < seq.length());
4.3215 + return 1;
4.3216 + }
4.3217 + int length = seq.length();
4.3218 + int x = index;
4.3219 + if (lengthInCodePoints >= 0) {
4.3220 + assert (index >= 0 && index < length);
4.3221 + for (int i = 0; x < length && i < lengthInCodePoints; i++) {
4.3222 + if (Character.isHighSurrogate(seq.charAt(x++))) {
4.3223 + if (x < length && Character.isLowSurrogate(seq.charAt(x))) {
4.3224 + x++;
4.3225 + }
4.3226 + }
4.3227 + }
4.3228 + return x - index;
4.3229 + }
4.3230 +
4.3231 + assert (index >= 0 && index <= length);
4.3232 + if (index == 0) {
4.3233 + return 0;
4.3234 + }
4.3235 + int len = -lengthInCodePoints;
4.3236 + for (int i = 0; x > 0 && i < len; i++) {
4.3237 + if (Character.isLowSurrogate(seq.charAt(--x))) {
4.3238 + if (x > 0 && Character.isHighSurrogate(seq.charAt(x-1))) {
4.3239 + x--;
4.3240 + }
4.3241 + }
4.3242 + }
4.3243 + return index - x;
4.3244 + }
4.3245 +
4.3246 + private static final int countCodePoints(CharSequence seq) {
4.3247 + int length = seq.length();
4.3248 + int n = 0;
4.3249 + for (int i = 0; i < length; ) {
4.3250 + n++;
4.3251 + if (Character.isHighSurrogate(seq.charAt(i++))) {
4.3252 + if (i < length && Character.isLowSurrogate(seq.charAt(i))) {
4.3253 + i++;
4.3254 + }
4.3255 + }
4.3256 + }
4.3257 + return n;
4.3258 + }
4.3259 +
4.3260 + /**
4.3261 + * Creates a bit vector for matching Latin-1 values. A normal BitClass
4.3262 + * never matches values above Latin-1, and a complemented BitClass always
4.3263 + * matches values above Latin-1.
4.3264 + */
4.3265 + private static final class BitClass extends BmpCharProperty {
4.3266 + final boolean[] bits;
4.3267 + BitClass() { bits = new boolean[256]; }
4.3268 + private BitClass(boolean[] bits) { this.bits = bits; }
4.3269 + BitClass add(int c, int flags) {
4.3270 + assert c >= 0 && c <= 255;
4.3271 + if ((flags & CASE_INSENSITIVE) != 0) {
4.3272 + if (ASCII.isAscii(c)) {
4.3273 + bits[ASCII.toUpper(c)] = true;
4.3274 + bits[ASCII.toLower(c)] = true;
4.3275 + } else if ((flags & UNICODE_CASE) != 0) {
4.3276 + bits[Character.toLowerCase(c)] = true;
4.3277 + bits[Character.toUpperCase(c)] = true;
4.3278 + }
4.3279 + }
4.3280 + bits[c] = true;
4.3281 + return this;
4.3282 + }
4.3283 + boolean isSatisfiedBy(int ch) {
4.3284 + return ch < 256 && bits[ch];
4.3285 + }
4.3286 + }
4.3287 +
4.3288 + /**
4.3289 + * Returns a suitably optimized, single character matcher.
4.3290 + */
4.3291 + private CharProperty newSingle(final int ch) {
4.3292 + if (has(CASE_INSENSITIVE)) {
4.3293 + int lower, upper;
4.3294 + if (has(UNICODE_CASE)) {
4.3295 + upper = Character.toUpperCase(ch);
4.3296 + lower = Character.toLowerCase(upper);
4.3297 + if (upper != lower)
4.3298 + return new SingleU(lower);
4.3299 + } else if (ASCII.isAscii(ch)) {
4.3300 + lower = ASCII.toLower(ch);
4.3301 + upper = ASCII.toUpper(ch);
4.3302 + if (lower != upper)
4.3303 + return new SingleI(lower, upper);
4.3304 + }
4.3305 + }
4.3306 + if (isSupplementary(ch))
4.3307 + return new SingleS(ch); // Match a given Unicode character
4.3308 + return new Single(ch); // Match a given BMP character
4.3309 + }
4.3310 +
4.3311 + /**
4.3312 + * Utility method for creating a string slice matcher.
4.3313 + */
4.3314 + private Node newSlice(int[] buf, int count, boolean hasSupplementary) {
4.3315 + int[] tmp = new int[count];
4.3316 + if (has(CASE_INSENSITIVE)) {
4.3317 + if (has(UNICODE_CASE)) {
4.3318 + for (int i = 0; i < count; i++) {
4.3319 + tmp[i] = Character.toLowerCase(
4.3320 + Character.toUpperCase(buf[i]));
4.3321 + }
4.3322 + return hasSupplementary? new SliceUS(tmp) : new SliceU(tmp);
4.3323 + }
4.3324 + for (int i = 0; i < count; i++) {
4.3325 + tmp[i] = ASCII.toLower(buf[i]);
4.3326 + }
4.3327 + return hasSupplementary? new SliceIS(tmp) : new SliceI(tmp);
4.3328 + }
4.3329 + for (int i = 0; i < count; i++) {
4.3330 + tmp[i] = buf[i];
4.3331 + }
4.3332 + return hasSupplementary ? new SliceS(tmp) : new Slice(tmp);
4.3333 + }
4.3334 +
4.3335 + /**
4.3336 + * The following classes are the building components of the object
4.3337 + * tree that represents a compiled regular expression. The object tree
4.3338 + * is made of individual elements that handle constructs in the Pattern.
4.3339 + * Each type of object knows how to match its equivalent construct with
4.3340 + * the match() method.
4.3341 + */
4.3342 +
4.3343 + /**
4.3344 + * Base class for all node classes. Subclasses should override the match()
4.3345 + * method as appropriate. This class is an accepting node, so its match()
4.3346 + * always returns true.
4.3347 + */
4.3348 + static class Node extends Object {
4.3349 + Node next;
4.3350 + Node() {
4.3351 + next = Pattern.accept;
4.3352 + }
4.3353 + /**
4.3354 + * This method implements the classic accept node.
4.3355 + */
4.3356 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3357 + matcher.last = i;
4.3358 + matcher.groups[0] = matcher.first;
4.3359 + matcher.groups[1] = matcher.last;
4.3360 + return true;
4.3361 + }
4.3362 + /**
4.3363 + * This method is good for all zero length assertions.
4.3364 + */
4.3365 + boolean study(TreeInfo info) {
4.3366 + if (next != null) {
4.3367 + return next.study(info);
4.3368 + } else {
4.3369 + return info.deterministic;
4.3370 + }
4.3371 + }
4.3372 + }
4.3373 +
4.3374 + static class LastNode extends Node {
4.3375 + /**
4.3376 + * This method implements the classic accept node with
4.3377 + * the addition of a check to see if the match occurred
4.3378 + * using all of the input.
4.3379 + */
4.3380 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3381 + if (matcher.acceptMode == Matcher.ENDANCHOR && i != matcher.to)
4.3382 + return false;
4.3383 + matcher.last = i;
4.3384 + matcher.groups[0] = matcher.first;
4.3385 + matcher.groups[1] = matcher.last;
4.3386 + return true;
4.3387 + }
4.3388 + }
4.3389 +
4.3390 + /**
4.3391 + * Used for REs that can start anywhere within the input string.
4.3392 + * This basically tries to match repeatedly at each spot in the
4.3393 + * input string, moving forward after each try. An anchored search
4.3394 + * or a BnM will bypass this node completely.
4.3395 + */
4.3396 + static class Start extends Node {
4.3397 + int minLength;
4.3398 + Start(Node node) {
4.3399 + this.next = node;
4.3400 + TreeInfo info = new TreeInfo();
4.3401 + next.study(info);
4.3402 + minLength = info.minLength;
4.3403 + }
4.3404 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3405 + if (i > matcher.to - minLength) {
4.3406 + matcher.hitEnd = true;
4.3407 + return false;
4.3408 + }
4.3409 + int guard = matcher.to - minLength;
4.3410 + for (; i <= guard; i++) {
4.3411 + if (next.match(matcher, i, seq)) {
4.3412 + matcher.first = i;
4.3413 + matcher.groups[0] = matcher.first;
4.3414 + matcher.groups[1] = matcher.last;
4.3415 + return true;
4.3416 + }
4.3417 + }
4.3418 + matcher.hitEnd = true;
4.3419 + return false;
4.3420 + }
4.3421 + boolean study(TreeInfo info) {
4.3422 + next.study(info);
4.3423 + info.maxValid = false;
4.3424 + info.deterministic = false;
4.3425 + return false;
4.3426 + }
4.3427 + }
4.3428 +
4.3429 + /*
4.3430 + * StartS supports supplementary characters, including unpaired surrogates.
4.3431 + */
4.3432 + static final class StartS extends Start {
4.3433 + StartS(Node node) {
4.3434 + super(node);
4.3435 + }
4.3436 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3437 + if (i > matcher.to - minLength) {
4.3438 + matcher.hitEnd = true;
4.3439 + return false;
4.3440 + }
4.3441 + int guard = matcher.to - minLength;
4.3442 + while (i <= guard) {
4.3443 + //if ((ret = next.match(matcher, i, seq)) || i == guard)
4.3444 + if (next.match(matcher, i, seq)) {
4.3445 + matcher.first = i;
4.3446 + matcher.groups[0] = matcher.first;
4.3447 + matcher.groups[1] = matcher.last;
4.3448 + return true;
4.3449 + }
4.3450 + if (i == guard)
4.3451 + break;
4.3452 + // Optimization to move to the next character. This is
4.3453 + // faster than countChars(seq, i, 1).
4.3454 + if (Character.isHighSurrogate(seq.charAt(i++))) {
4.3455 + if (i < seq.length() &&
4.3456 + Character.isLowSurrogate(seq.charAt(i))) {
4.3457 + i++;
4.3458 + }
4.3459 + }
4.3460 + }
4.3461 + matcher.hitEnd = true;
4.3462 + return false;
4.3463 + }
4.3464 + }
4.3465 +
4.3466 + /**
4.3467 + * Node to anchor at the beginning of input. This object implements the
4.3468 + * match for a \A sequence, and the caret anchor will use this if not in
4.3469 + * multiline mode.
4.3470 + */
4.3471 + static final class Begin extends Node {
4.3472 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3473 + int fromIndex = (matcher.anchoringBounds) ?
4.3474 + matcher.from : 0;
4.3475 + if (i == fromIndex && next.match(matcher, i, seq)) {
4.3476 + matcher.first = i;
4.3477 + matcher.groups[0] = i;
4.3478 + matcher.groups[1] = matcher.last;
4.3479 + return true;
4.3480 + } else {
4.3481 + return false;
4.3482 + }
4.3483 + }
4.3484 + }
4.3485 +
4.3486 + /**
4.3487 + * Node to anchor at the end of input. This is the absolute end, so this
4.3488 + * should not match at the last newline before the end as $ will.
4.3489 + */
4.3490 + static final class End extends Node {
4.3491 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3492 + int endIndex = (matcher.anchoringBounds) ?
4.3493 + matcher.to : matcher.getTextLength();
4.3494 + if (i == endIndex) {
4.3495 + matcher.hitEnd = true;
4.3496 + return next.match(matcher, i, seq);
4.3497 + }
4.3498 + return false;
4.3499 + }
4.3500 + }
4.3501 +
4.3502 + /**
4.3503 + * Node to anchor at the beginning of a line. This is essentially the
4.3504 + * object to match for the multiline ^.
4.3505 + */
4.3506 + static final class Caret extends Node {
4.3507 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3508 + int startIndex = matcher.from;
4.3509 + int endIndex = matcher.to;
4.3510 + if (!matcher.anchoringBounds) {
4.3511 + startIndex = 0;
4.3512 + endIndex = matcher.getTextLength();
4.3513 + }
4.3514 + // Perl does not match ^ at end of input even after newline
4.3515 + if (i == endIndex) {
4.3516 + matcher.hitEnd = true;
4.3517 + return false;
4.3518 + }
4.3519 + if (i > startIndex) {
4.3520 + char ch = seq.charAt(i-1);
4.3521 + if (ch != '\n' && ch != '\r'
4.3522 + && (ch|1) != '\u2029'
4.3523 + && ch != '\u0085' ) {
4.3524 + return false;
4.3525 + }
4.3526 + // Should treat /r/n as one newline
4.3527 + if (ch == '\r' && seq.charAt(i) == '\n')
4.3528 + return false;
4.3529 + }
4.3530 + return next.match(matcher, i, seq);
4.3531 + }
4.3532 + }
4.3533 +
4.3534 + /**
4.3535 + * Node to anchor at the beginning of a line when in unixdot mode.
4.3536 + */
4.3537 + static final class UnixCaret extends Node {
4.3538 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3539 + int startIndex = matcher.from;
4.3540 + int endIndex = matcher.to;
4.3541 + if (!matcher.anchoringBounds) {
4.3542 + startIndex = 0;
4.3543 + endIndex = matcher.getTextLength();
4.3544 + }
4.3545 + // Perl does not match ^ at end of input even after newline
4.3546 + if (i == endIndex) {
4.3547 + matcher.hitEnd = true;
4.3548 + return false;
4.3549 + }
4.3550 + if (i > startIndex) {
4.3551 + char ch = seq.charAt(i-1);
4.3552 + if (ch != '\n') {
4.3553 + return false;
4.3554 + }
4.3555 + }
4.3556 + return next.match(matcher, i, seq);
4.3557 + }
4.3558 + }
4.3559 +
4.3560 + /**
4.3561 + * Node to match the location where the last match ended.
4.3562 + * This is used for the \G construct.
4.3563 + */
4.3564 + static final class LastMatch extends Node {
4.3565 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3566 + if (i != matcher.oldLast)
4.3567 + return false;
4.3568 + return next.match(matcher, i, seq);
4.3569 + }
4.3570 + }
4.3571 +
4.3572 + /**
4.3573 + * Node to anchor at the end of a line or the end of input based on the
4.3574 + * multiline mode.
4.3575 + *
4.3576 + * When not in multiline mode, the $ can only match at the very end
4.3577 + * of the input, unless the input ends in a line terminator in which
4.3578 + * it matches right before the last line terminator.
4.3579 + *
4.3580 + * Note that \r\n is considered an atomic line terminator.
4.3581 + *
4.3582 + * Like ^ the $ operator matches at a position, it does not match the
4.3583 + * line terminators themselves.
4.3584 + */
4.3585 + static final class Dollar extends Node {
4.3586 + boolean multiline;
4.3587 + Dollar(boolean mul) {
4.3588 + multiline = mul;
4.3589 + }
4.3590 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3591 + int endIndex = (matcher.anchoringBounds) ?
4.3592 + matcher.to : matcher.getTextLength();
4.3593 + if (!multiline) {
4.3594 + if (i < endIndex - 2)
4.3595 + return false;
4.3596 + if (i == endIndex - 2) {
4.3597 + char ch = seq.charAt(i);
4.3598 + if (ch != '\r')
4.3599 + return false;
4.3600 + ch = seq.charAt(i + 1);
4.3601 + if (ch != '\n')
4.3602 + return false;
4.3603 + }
4.3604 + }
4.3605 + // Matches before any line terminator; also matches at the
4.3606 + // end of input
4.3607 + // Before line terminator:
4.3608 + // If multiline, we match here no matter what
4.3609 + // If not multiline, fall through so that the end
4.3610 + // is marked as hit; this must be a /r/n or a /n
4.3611 + // at the very end so the end was hit; more input
4.3612 + // could make this not match here
4.3613 + if (i < endIndex) {
4.3614 + char ch = seq.charAt(i);
4.3615 + if (ch == '\n') {
4.3616 + // No match between \r\n
4.3617 + if (i > 0 && seq.charAt(i-1) == '\r')
4.3618 + return false;
4.3619 + if (multiline)
4.3620 + return next.match(matcher, i, seq);
4.3621 + } else if (ch == '\r' || ch == '\u0085' ||
4.3622 + (ch|1) == '\u2029') {
4.3623 + if (multiline)
4.3624 + return next.match(matcher, i, seq);
4.3625 + } else { // No line terminator, no match
4.3626 + return false;
4.3627 + }
4.3628 + }
4.3629 + // Matched at current end so hit end
4.3630 + matcher.hitEnd = true;
4.3631 + // If a $ matches because of end of input, then more input
4.3632 + // could cause it to fail!
4.3633 + matcher.requireEnd = true;
4.3634 + return next.match(matcher, i, seq);
4.3635 + }
4.3636 + boolean study(TreeInfo info) {
4.3637 + next.study(info);
4.3638 + return info.deterministic;
4.3639 + }
4.3640 + }
4.3641 +
4.3642 + /**
4.3643 + * Node to anchor at the end of a line or the end of input based on the
4.3644 + * multiline mode when in unix lines mode.
4.3645 + */
4.3646 + static final class UnixDollar extends Node {
4.3647 + boolean multiline;
4.3648 + UnixDollar(boolean mul) {
4.3649 + multiline = mul;
4.3650 + }
4.3651 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3652 + int endIndex = (matcher.anchoringBounds) ?
4.3653 + matcher.to : matcher.getTextLength();
4.3654 + if (i < endIndex) {
4.3655 + char ch = seq.charAt(i);
4.3656 + if (ch == '\n') {
4.3657 + // If not multiline, then only possible to
4.3658 + // match at very end or one before end
4.3659 + if (multiline == false && i != endIndex - 1)
4.3660 + return false;
4.3661 + // If multiline return next.match without setting
4.3662 + // matcher.hitEnd
4.3663 + if (multiline)
4.3664 + return next.match(matcher, i, seq);
4.3665 + } else {
4.3666 + return false;
4.3667 + }
4.3668 + }
4.3669 + // Matching because at the end or 1 before the end;
4.3670 + // more input could change this so set hitEnd
4.3671 + matcher.hitEnd = true;
4.3672 + // If a $ matches because of end of input, then more input
4.3673 + // could cause it to fail!
4.3674 + matcher.requireEnd = true;
4.3675 + return next.match(matcher, i, seq);
4.3676 + }
4.3677 + boolean study(TreeInfo info) {
4.3678 + next.study(info);
4.3679 + return info.deterministic;
4.3680 + }
4.3681 + }
4.3682 +
4.3683 + /**
4.3684 + * Abstract node class to match one character satisfying some
4.3685 + * boolean property.
4.3686 + */
4.3687 + private static abstract class CharProperty extends Node {
4.3688 + abstract boolean isSatisfiedBy(int ch);
4.3689 + CharProperty complement() {
4.3690 + return new CharProperty() {
4.3691 + boolean isSatisfiedBy(int ch) {
4.3692 + return ! CharProperty.this.isSatisfiedBy(ch);}};
4.3693 + }
4.3694 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3695 + if (i < matcher.to) {
4.3696 + int ch = Character.codePointAt(seq, i);
4.3697 + return isSatisfiedBy(ch)
4.3698 + && next.match(matcher, i+Character.charCount(ch), seq);
4.3699 + } else {
4.3700 + matcher.hitEnd = true;
4.3701 + return false;
4.3702 + }
4.3703 + }
4.3704 + boolean study(TreeInfo info) {
4.3705 + info.minLength++;
4.3706 + info.maxLength++;
4.3707 + return next.study(info);
4.3708 + }
4.3709 + }
4.3710 +
4.3711 + /**
4.3712 + * Optimized version of CharProperty that works only for
4.3713 + * properties never satisfied by Supplementary characters.
4.3714 + */
4.3715 + private static abstract class BmpCharProperty extends CharProperty {
4.3716 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3717 + if (i < matcher.to) {
4.3718 + return isSatisfiedBy(seq.charAt(i))
4.3719 + && next.match(matcher, i+1, seq);
4.3720 + } else {
4.3721 + matcher.hitEnd = true;
4.3722 + return false;
4.3723 + }
4.3724 + }
4.3725 + }
4.3726 +
4.3727 + /**
4.3728 + * Node class that matches a Supplementary Unicode character
4.3729 + */
4.3730 + static final class SingleS extends CharProperty {
4.3731 + final int c;
4.3732 + SingleS(int c) { this.c = c; }
4.3733 + boolean isSatisfiedBy(int ch) {
4.3734 + return ch == c;
4.3735 + }
4.3736 + }
4.3737 +
4.3738 + /**
4.3739 + * Optimization -- matches a given BMP character
4.3740 + */
4.3741 + static final class Single extends BmpCharProperty {
4.3742 + final int c;
4.3743 + Single(int c) { this.c = c; }
4.3744 + boolean isSatisfiedBy(int ch) {
4.3745 + return ch == c;
4.3746 + }
4.3747 + }
4.3748 +
4.3749 + /**
4.3750 + * Case insensitive matches a given BMP character
4.3751 + */
4.3752 + static final class SingleI extends BmpCharProperty {
4.3753 + final int lower;
4.3754 + final int upper;
4.3755 + SingleI(int lower, int upper) {
4.3756 + this.lower = lower;
4.3757 + this.upper = upper;
4.3758 + }
4.3759 + boolean isSatisfiedBy(int ch) {
4.3760 + return ch == lower || ch == upper;
4.3761 + }
4.3762 + }
4.3763 +
4.3764 + /**
4.3765 + * Unicode case insensitive matches a given Unicode character
4.3766 + */
4.3767 + static final class SingleU extends CharProperty {
4.3768 + final int lower;
4.3769 + SingleU(int lower) {
4.3770 + this.lower = lower;
4.3771 + }
4.3772 + boolean isSatisfiedBy(int ch) {
4.3773 + return lower == ch ||
4.3774 + lower == Character.toLowerCase(Character.toUpperCase(ch));
4.3775 + }
4.3776 + }
4.3777 +
4.3778 +
4.3779 + /**
4.3780 + * Node class that matches a Unicode block.
4.3781 + */
4.3782 + static final class Block extends CharProperty {
4.3783 + final Character.UnicodeBlock block;
4.3784 + Block(Character.UnicodeBlock block) {
4.3785 + this.block = block;
4.3786 + }
4.3787 + boolean isSatisfiedBy(int ch) {
4.3788 + return block == Character.UnicodeBlock.of(ch);
4.3789 + }
4.3790 + }
4.3791 +
4.3792 + /**
4.3793 + * Node class that matches a Unicode script
4.3794 + */
4.3795 + static final class Script extends CharProperty {
4.3796 + final Character.UnicodeScript script;
4.3797 + Script(Character.UnicodeScript script) {
4.3798 + this.script = script;
4.3799 + }
4.3800 + boolean isSatisfiedBy(int ch) {
4.3801 + return script == Character.UnicodeScript.of(ch);
4.3802 + }
4.3803 + }
4.3804 +
4.3805 + /**
4.3806 + * Node class that matches a Unicode category.
4.3807 + */
4.3808 + static final class Category extends CharProperty {
4.3809 + final int typeMask;
4.3810 + Category(int typeMask) { this.typeMask = typeMask; }
4.3811 + boolean isSatisfiedBy(int ch) {
4.3812 + return (typeMask & (1 << Character.getType(ch))) != 0;
4.3813 + }
4.3814 + }
4.3815 +
4.3816 + /**
4.3817 + * Node class that matches a Unicode "type"
4.3818 + */
4.3819 + static final class Utype extends CharProperty {
4.3820 + final UnicodeProp uprop;
4.3821 + Utype(UnicodeProp uprop) { this.uprop = uprop; }
4.3822 + boolean isSatisfiedBy(int ch) {
4.3823 + return uprop.is(ch);
4.3824 + }
4.3825 + }
4.3826 +
4.3827 +
4.3828 + /**
4.3829 + * Node class that matches a POSIX type.
4.3830 + */
4.3831 + static final class Ctype extends BmpCharProperty {
4.3832 + final int ctype;
4.3833 + Ctype(int ctype) { this.ctype = ctype; }
4.3834 + boolean isSatisfiedBy(int ch) {
4.3835 + return ch < 128 && ASCII.isType(ch, ctype);
4.3836 + }
4.3837 + }
4.3838 +
4.3839 + /**
4.3840 + * Base class for all Slice nodes
4.3841 + */
4.3842 + static class SliceNode extends Node {
4.3843 + int[] buffer;
4.3844 + SliceNode(int[] buf) {
4.3845 + buffer = buf;
4.3846 + }
4.3847 + boolean study(TreeInfo info) {
4.3848 + info.minLength += buffer.length;
4.3849 + info.maxLength += buffer.length;
4.3850 + return next.study(info);
4.3851 + }
4.3852 + }
4.3853 +
4.3854 + /**
4.3855 + * Node class for a case sensitive/BMP-only sequence of literal
4.3856 + * characters.
4.3857 + */
4.3858 + static final class Slice extends SliceNode {
4.3859 + Slice(int[] buf) {
4.3860 + super(buf);
4.3861 + }
4.3862 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3863 + int[] buf = buffer;
4.3864 + int len = buf.length;
4.3865 + for (int j=0; j<len; j++) {
4.3866 + if ((i+j) >= matcher.to) {
4.3867 + matcher.hitEnd = true;
4.3868 + return false;
4.3869 + }
4.3870 + if (buf[j] != seq.charAt(i+j))
4.3871 + return false;
4.3872 + }
4.3873 + return next.match(matcher, i+len, seq);
4.3874 + }
4.3875 + }
4.3876 +
4.3877 + /**
4.3878 + * Node class for a case_insensitive/BMP-only sequence of literal
4.3879 + * characters.
4.3880 + */
4.3881 + static class SliceI extends SliceNode {
4.3882 + SliceI(int[] buf) {
4.3883 + super(buf);
4.3884 + }
4.3885 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3886 + int[] buf = buffer;
4.3887 + int len = buf.length;
4.3888 + for (int j=0; j<len; j++) {
4.3889 + if ((i+j) >= matcher.to) {
4.3890 + matcher.hitEnd = true;
4.3891 + return false;
4.3892 + }
4.3893 + int c = seq.charAt(i+j);
4.3894 + if (buf[j] != c &&
4.3895 + buf[j] != ASCII.toLower(c))
4.3896 + return false;
4.3897 + }
4.3898 + return next.match(matcher, i+len, seq);
4.3899 + }
4.3900 + }
4.3901 +
4.3902 + /**
4.3903 + * Node class for a unicode_case_insensitive/BMP-only sequence of
4.3904 + * literal characters. Uses unicode case folding.
4.3905 + */
4.3906 + static final class SliceU extends SliceNode {
4.3907 + SliceU(int[] buf) {
4.3908 + super(buf);
4.3909 + }
4.3910 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3911 + int[] buf = buffer;
4.3912 + int len = buf.length;
4.3913 + for (int j=0; j<len; j++) {
4.3914 + if ((i+j) >= matcher.to) {
4.3915 + matcher.hitEnd = true;
4.3916 + return false;
4.3917 + }
4.3918 + int c = seq.charAt(i+j);
4.3919 + if (buf[j] != c &&
4.3920 + buf[j] != Character.toLowerCase(Character.toUpperCase(c)))
4.3921 + return false;
4.3922 + }
4.3923 + return next.match(matcher, i+len, seq);
4.3924 + }
4.3925 + }
4.3926 +
4.3927 + /**
4.3928 + * Node class for a case sensitive sequence of literal characters
4.3929 + * including supplementary characters.
4.3930 + */
4.3931 + static final class SliceS extends SliceNode {
4.3932 + SliceS(int[] buf) {
4.3933 + super(buf);
4.3934 + }
4.3935 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3936 + int[] buf = buffer;
4.3937 + int x = i;
4.3938 + for (int j = 0; j < buf.length; j++) {
4.3939 + if (x >= matcher.to) {
4.3940 + matcher.hitEnd = true;
4.3941 + return false;
4.3942 + }
4.3943 + int c = Character.codePointAt(seq, x);
4.3944 + if (buf[j] != c)
4.3945 + return false;
4.3946 + x += Character.charCount(c);
4.3947 + if (x > matcher.to) {
4.3948 + matcher.hitEnd = true;
4.3949 + return false;
4.3950 + }
4.3951 + }
4.3952 + return next.match(matcher, x, seq);
4.3953 + }
4.3954 + }
4.3955 +
4.3956 + /**
4.3957 + * Node class for a case insensitive sequence of literal characters
4.3958 + * including supplementary characters.
4.3959 + */
4.3960 + static class SliceIS extends SliceNode {
4.3961 + SliceIS(int[] buf) {
4.3962 + super(buf);
4.3963 + }
4.3964 + int toLower(int c) {
4.3965 + return ASCII.toLower(c);
4.3966 + }
4.3967 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.3968 + int[] buf = buffer;
4.3969 + int x = i;
4.3970 + for (int j = 0; j < buf.length; j++) {
4.3971 + if (x >= matcher.to) {
4.3972 + matcher.hitEnd = true;
4.3973 + return false;
4.3974 + }
4.3975 + int c = Character.codePointAt(seq, x);
4.3976 + if (buf[j] != c && buf[j] != toLower(c))
4.3977 + return false;
4.3978 + x += Character.charCount(c);
4.3979 + if (x > matcher.to) {
4.3980 + matcher.hitEnd = true;
4.3981 + return false;
4.3982 + }
4.3983 + }
4.3984 + return next.match(matcher, x, seq);
4.3985 + }
4.3986 + }
4.3987 +
4.3988 + /**
4.3989 + * Node class for a case insensitive sequence of literal characters.
4.3990 + * Uses unicode case folding.
4.3991 + */
4.3992 + static final class SliceUS extends SliceIS {
4.3993 + SliceUS(int[] buf) {
4.3994 + super(buf);
4.3995 + }
4.3996 + int toLower(int c) {
4.3997 + return Character.toLowerCase(Character.toUpperCase(c));
4.3998 + }
4.3999 + }
4.4000 +
4.4001 + private static boolean inRange(int lower, int ch, int upper) {
4.4002 + return lower <= ch && ch <= upper;
4.4003 + }
4.4004 +
4.4005 + /**
4.4006 + * Returns node for matching characters within an explicit value range.
4.4007 + */
4.4008 + private static CharProperty rangeFor(final int lower,
4.4009 + final int upper) {
4.4010 + return new CharProperty() {
4.4011 + boolean isSatisfiedBy(int ch) {
4.4012 + return inRange(lower, ch, upper);}};
4.4013 + }
4.4014 +
4.4015 + /**
4.4016 + * Returns node for matching characters within an explicit value
4.4017 + * range in a case insensitive manner.
4.4018 + */
4.4019 + private CharProperty caseInsensitiveRangeFor(final int lower,
4.4020 + final int upper) {
4.4021 + if (has(UNICODE_CASE))
4.4022 + return new CharProperty() {
4.4023 + boolean isSatisfiedBy(int ch) {
4.4024 + if (inRange(lower, ch, upper))
4.4025 + return true;
4.4026 + int up = Character.toUpperCase(ch);
4.4027 + return inRange(lower, up, upper) ||
4.4028 + inRange(lower, Character.toLowerCase(up), upper);}};
4.4029 + return new CharProperty() {
4.4030 + boolean isSatisfiedBy(int ch) {
4.4031 + return inRange(lower, ch, upper) ||
4.4032 + ASCII.isAscii(ch) &&
4.4033 + (inRange(lower, ASCII.toUpper(ch), upper) ||
4.4034 + inRange(lower, ASCII.toLower(ch), upper));
4.4035 + }};
4.4036 + }
4.4037 +
4.4038 + /**
4.4039 + * Implements the Unicode category ALL and the dot metacharacter when
4.4040 + * in dotall mode.
4.4041 + */
4.4042 + static final class All extends CharProperty {
4.4043 + boolean isSatisfiedBy(int ch) {
4.4044 + return true;
4.4045 + }
4.4046 + }
4.4047 +
4.4048 + /**
4.4049 + * Node class for the dot metacharacter when dotall is not enabled.
4.4050 + */
4.4051 + static final class Dot extends CharProperty {
4.4052 + boolean isSatisfiedBy(int ch) {
4.4053 + return (ch != '\n' && ch != '\r'
4.4054 + && (ch|1) != '\u2029'
4.4055 + && ch != '\u0085');
4.4056 + }
4.4057 + }
4.4058 +
4.4059 + /**
4.4060 + * Node class for the dot metacharacter when dotall is not enabled
4.4061 + * but UNIX_LINES is enabled.
4.4062 + */
4.4063 + static final class UnixDot extends CharProperty {
4.4064 + boolean isSatisfiedBy(int ch) {
4.4065 + return ch != '\n';
4.4066 + }
4.4067 + }
4.4068 +
4.4069 + /**
4.4070 + * The 0 or 1 quantifier. This one class implements all three types.
4.4071 + */
4.4072 + static final class Ques extends Node {
4.4073 + Node atom;
4.4074 + int type;
4.4075 + Ques(Node node, int type) {
4.4076 + this.atom = node;
4.4077 + this.type = type;
4.4078 + }
4.4079 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4080 + switch (type) {
4.4081 + case GREEDY:
4.4082 + return (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq))
4.4083 + || next.match(matcher, i, seq);
4.4084 + case LAZY:
4.4085 + return next.match(matcher, i, seq)
4.4086 + || (atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq));
4.4087 + case POSSESSIVE:
4.4088 + if (atom.match(matcher, i, seq)) i = matcher.last;
4.4089 + return next.match(matcher, i, seq);
4.4090 + default:
4.4091 + return atom.match(matcher, i, seq) && next.match(matcher, matcher.last, seq);
4.4092 + }
4.4093 + }
4.4094 + boolean study(TreeInfo info) {
4.4095 + if (type != INDEPENDENT) {
4.4096 + int minL = info.minLength;
4.4097 + atom.study(info);
4.4098 + info.minLength = minL;
4.4099 + info.deterministic = false;
4.4100 + return next.study(info);
4.4101 + } else {
4.4102 + atom.study(info);
4.4103 + return next.study(info);
4.4104 + }
4.4105 + }
4.4106 + }
4.4107 +
4.4108 + /**
4.4109 + * Handles the curly-brace style repetition with a specified minimum and
4.4110 + * maximum occurrences. The * quantifier is handled as a special case.
4.4111 + * This class handles the three types.
4.4112 + */
4.4113 + static final class Curly extends Node {
4.4114 + Node atom;
4.4115 + int type;
4.4116 + int cmin;
4.4117 + int cmax;
4.4118 +
4.4119 + Curly(Node node, int cmin, int cmax, int type) {
4.4120 + this.atom = node;
4.4121 + this.type = type;
4.4122 + this.cmin = cmin;
4.4123 + this.cmax = cmax;
4.4124 + }
4.4125 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4126 + int j;
4.4127 + for (j = 0; j < cmin; j++) {
4.4128 + if (atom.match(matcher, i, seq)) {
4.4129 + i = matcher.last;
4.4130 + continue;
4.4131 + }
4.4132 + return false;
4.4133 + }
4.4134 + if (type == GREEDY)
4.4135 + return match0(matcher, i, j, seq);
4.4136 + else if (type == LAZY)
4.4137 + return match1(matcher, i, j, seq);
4.4138 + else
4.4139 + return match2(matcher, i, j, seq);
4.4140 + }
4.4141 + // Greedy match.
4.4142 + // i is the index to start matching at
4.4143 + // j is the number of atoms that have matched
4.4144 + boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
4.4145 + if (j >= cmax) {
4.4146 + // We have matched the maximum... continue with the rest of
4.4147 + // the regular expression
4.4148 + return next.match(matcher, i, seq);
4.4149 + }
4.4150 + int backLimit = j;
4.4151 + while (atom.match(matcher, i, seq)) {
4.4152 + // k is the length of this match
4.4153 + int k = matcher.last - i;
4.4154 + if (k == 0) // Zero length match
4.4155 + break;
4.4156 + // Move up index and number matched
4.4157 + i = matcher.last;
4.4158 + j++;
4.4159 + // We are greedy so match as many as we can
4.4160 + while (j < cmax) {
4.4161 + if (!atom.match(matcher, i, seq))
4.4162 + break;
4.4163 + if (i + k != matcher.last) {
4.4164 + if (match0(matcher, matcher.last, j+1, seq))
4.4165 + return true;
4.4166 + break;
4.4167 + }
4.4168 + i += k;
4.4169 + j++;
4.4170 + }
4.4171 + // Handle backing off if match fails
4.4172 + while (j >= backLimit) {
4.4173 + if (next.match(matcher, i, seq))
4.4174 + return true;
4.4175 + i -= k;
4.4176 + j--;
4.4177 + }
4.4178 + return false;
4.4179 + }
4.4180 + return next.match(matcher, i, seq);
4.4181 + }
4.4182 + // Reluctant match. At this point, the minimum has been satisfied.
4.4183 + // i is the index to start matching at
4.4184 + // j is the number of atoms that have matched
4.4185 + boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
4.4186 + for (;;) {
4.4187 + // Try finishing match without consuming any more
4.4188 + if (next.match(matcher, i, seq))
4.4189 + return true;
4.4190 + // At the maximum, no match found
4.4191 + if (j >= cmax)
4.4192 + return false;
4.4193 + // Okay, must try one more atom
4.4194 + if (!atom.match(matcher, i, seq))
4.4195 + return false;
4.4196 + // If we haven't moved forward then must break out
4.4197 + if (i == matcher.last)
4.4198 + return false;
4.4199 + // Move up index and number matched
4.4200 + i = matcher.last;
4.4201 + j++;
4.4202 + }
4.4203 + }
4.4204 + boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
4.4205 + for (; j < cmax; j++) {
4.4206 + if (!atom.match(matcher, i, seq))
4.4207 + break;
4.4208 + if (i == matcher.last)
4.4209 + break;
4.4210 + i = matcher.last;
4.4211 + }
4.4212 + return next.match(matcher, i, seq);
4.4213 + }
4.4214 + boolean study(TreeInfo info) {
4.4215 + // Save original info
4.4216 + int minL = info.minLength;
4.4217 + int maxL = info.maxLength;
4.4218 + boolean maxV = info.maxValid;
4.4219 + boolean detm = info.deterministic;
4.4220 + info.reset();
4.4221 +
4.4222 + atom.study(info);
4.4223 +
4.4224 + int temp = info.minLength * cmin + minL;
4.4225 + if (temp < minL) {
4.4226 + temp = 0xFFFFFFF; // arbitrary large number
4.4227 + }
4.4228 + info.minLength = temp;
4.4229 +
4.4230 + if (maxV & info.maxValid) {
4.4231 + temp = info.maxLength * cmax + maxL;
4.4232 + info.maxLength = temp;
4.4233 + if (temp < maxL) {
4.4234 + info.maxValid = false;
4.4235 + }
4.4236 + } else {
4.4237 + info.maxValid = false;
4.4238 + }
4.4239 +
4.4240 + if (info.deterministic && cmin == cmax)
4.4241 + info.deterministic = detm;
4.4242 + else
4.4243 + info.deterministic = false;
4.4244 +
4.4245 + return next.study(info);
4.4246 + }
4.4247 + }
4.4248 +
4.4249 + /**
4.4250 + * Handles the curly-brace style repetition with a specified minimum and
4.4251 + * maximum occurrences in deterministic cases. This is an iterative
4.4252 + * optimization over the Prolog and Loop system which would handle this
4.4253 + * in a recursive way. The * quantifier is handled as a special case.
4.4254 + * If capture is true then this class saves group settings and ensures
4.4255 + * that groups are unset when backing off of a group match.
4.4256 + */
4.4257 + static final class GroupCurly extends Node {
4.4258 + Node atom;
4.4259 + int type;
4.4260 + int cmin;
4.4261 + int cmax;
4.4262 + int localIndex;
4.4263 + int groupIndex;
4.4264 + boolean capture;
4.4265 +
4.4266 + GroupCurly(Node node, int cmin, int cmax, int type, int local,
4.4267 + int group, boolean capture) {
4.4268 + this.atom = node;
4.4269 + this.type = type;
4.4270 + this.cmin = cmin;
4.4271 + this.cmax = cmax;
4.4272 + this.localIndex = local;
4.4273 + this.groupIndex = group;
4.4274 + this.capture = capture;
4.4275 + }
4.4276 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4277 + int[] groups = matcher.groups;
4.4278 + int[] locals = matcher.locals;
4.4279 + int save0 = locals[localIndex];
4.4280 + int save1 = 0;
4.4281 + int save2 = 0;
4.4282 +
4.4283 + if (capture) {
4.4284 + save1 = groups[groupIndex];
4.4285 + save2 = groups[groupIndex+1];
4.4286 + }
4.4287 +
4.4288 + // Notify GroupTail there is no need to setup group info
4.4289 + // because it will be set here
4.4290 + locals[localIndex] = -1;
4.4291 +
4.4292 + boolean ret = true;
4.4293 + for (int j = 0; j < cmin; j++) {
4.4294 + if (atom.match(matcher, i, seq)) {
4.4295 + if (capture) {
4.4296 + groups[groupIndex] = i;
4.4297 + groups[groupIndex+1] = matcher.last;
4.4298 + }
4.4299 + i = matcher.last;
4.4300 + } else {
4.4301 + ret = false;
4.4302 + break;
4.4303 + }
4.4304 + }
4.4305 + if (ret) {
4.4306 + if (type == GREEDY) {
4.4307 + ret = match0(matcher, i, cmin, seq);
4.4308 + } else if (type == LAZY) {
4.4309 + ret = match1(matcher, i, cmin, seq);
4.4310 + } else {
4.4311 + ret = match2(matcher, i, cmin, seq);
4.4312 + }
4.4313 + }
4.4314 + if (!ret) {
4.4315 + locals[localIndex] = save0;
4.4316 + if (capture) {
4.4317 + groups[groupIndex] = save1;
4.4318 + groups[groupIndex+1] = save2;
4.4319 + }
4.4320 + }
4.4321 + return ret;
4.4322 + }
4.4323 + // Aggressive group match
4.4324 + boolean match0(Matcher matcher, int i, int j, CharSequence seq) {
4.4325 + int[] groups = matcher.groups;
4.4326 + int save0 = 0;
4.4327 + int save1 = 0;
4.4328 + if (capture) {
4.4329 + save0 = groups[groupIndex];
4.4330 + save1 = groups[groupIndex+1];
4.4331 + }
4.4332 + for (;;) {
4.4333 + if (j >= cmax)
4.4334 + break;
4.4335 + if (!atom.match(matcher, i, seq))
4.4336 + break;
4.4337 + int k = matcher.last - i;
4.4338 + if (k <= 0) {
4.4339 + if (capture) {
4.4340 + groups[groupIndex] = i;
4.4341 + groups[groupIndex+1] = i + k;
4.4342 + }
4.4343 + i = i + k;
4.4344 + break;
4.4345 + }
4.4346 + for (;;) {
4.4347 + if (capture) {
4.4348 + groups[groupIndex] = i;
4.4349 + groups[groupIndex+1] = i + k;
4.4350 + }
4.4351 + i = i + k;
4.4352 + if (++j >= cmax)
4.4353 + break;
4.4354 + if (!atom.match(matcher, i, seq))
4.4355 + break;
4.4356 + if (i + k != matcher.last) {
4.4357 + if (match0(matcher, i, j, seq))
4.4358 + return true;
4.4359 + break;
4.4360 + }
4.4361 + }
4.4362 + while (j > cmin) {
4.4363 + if (next.match(matcher, i, seq)) {
4.4364 + if (capture) {
4.4365 + groups[groupIndex+1] = i;
4.4366 + groups[groupIndex] = i - k;
4.4367 + }
4.4368 + i = i - k;
4.4369 + return true;
4.4370 + }
4.4371 + // backing off
4.4372 + if (capture) {
4.4373 + groups[groupIndex+1] = i;
4.4374 + groups[groupIndex] = i - k;
4.4375 + }
4.4376 + i = i - k;
4.4377 + j--;
4.4378 + }
4.4379 + break;
4.4380 + }
4.4381 + if (capture) {
4.4382 + groups[groupIndex] = save0;
4.4383 + groups[groupIndex+1] = save1;
4.4384 + }
4.4385 + return next.match(matcher, i, seq);
4.4386 + }
4.4387 + // Reluctant matching
4.4388 + boolean match1(Matcher matcher, int i, int j, CharSequence seq) {
4.4389 + for (;;) {
4.4390 + if (next.match(matcher, i, seq))
4.4391 + return true;
4.4392 + if (j >= cmax)
4.4393 + return false;
4.4394 + if (!atom.match(matcher, i, seq))
4.4395 + return false;
4.4396 + if (i == matcher.last)
4.4397 + return false;
4.4398 + if (capture) {
4.4399 + matcher.groups[groupIndex] = i;
4.4400 + matcher.groups[groupIndex+1] = matcher.last;
4.4401 + }
4.4402 + i = matcher.last;
4.4403 + j++;
4.4404 + }
4.4405 + }
4.4406 + // Possessive matching
4.4407 + boolean match2(Matcher matcher, int i, int j, CharSequence seq) {
4.4408 + for (; j < cmax; j++) {
4.4409 + if (!atom.match(matcher, i, seq)) {
4.4410 + break;
4.4411 + }
4.4412 + if (capture) {
4.4413 + matcher.groups[groupIndex] = i;
4.4414 + matcher.groups[groupIndex+1] = matcher.last;
4.4415 + }
4.4416 + if (i == matcher.last) {
4.4417 + break;
4.4418 + }
4.4419 + i = matcher.last;
4.4420 + }
4.4421 + return next.match(matcher, i, seq);
4.4422 + }
4.4423 + boolean study(TreeInfo info) {
4.4424 + // Save original info
4.4425 + int minL = info.minLength;
4.4426 + int maxL = info.maxLength;
4.4427 + boolean maxV = info.maxValid;
4.4428 + boolean detm = info.deterministic;
4.4429 + info.reset();
4.4430 +
4.4431 + atom.study(info);
4.4432 +
4.4433 + int temp = info.minLength * cmin + minL;
4.4434 + if (temp < minL) {
4.4435 + temp = 0xFFFFFFF; // Arbitrary large number
4.4436 + }
4.4437 + info.minLength = temp;
4.4438 +
4.4439 + if (maxV & info.maxValid) {
4.4440 + temp = info.maxLength * cmax + maxL;
4.4441 + info.maxLength = temp;
4.4442 + if (temp < maxL) {
4.4443 + info.maxValid = false;
4.4444 + }
4.4445 + } else {
4.4446 + info.maxValid = false;
4.4447 + }
4.4448 +
4.4449 + if (info.deterministic && cmin == cmax) {
4.4450 + info.deterministic = detm;
4.4451 + } else {
4.4452 + info.deterministic = false;
4.4453 + }
4.4454 +
4.4455 + return next.study(info);
4.4456 + }
4.4457 + }
4.4458 +
4.4459 + /**
4.4460 + * A Guard node at the end of each atom node in a Branch. It
4.4461 + * serves the purpose of chaining the "match" operation to
4.4462 + * "next" but not the "study", so we can collect the TreeInfo
4.4463 + * of each atom node without including the TreeInfo of the
4.4464 + * "next".
4.4465 + */
4.4466 + static final class BranchConn extends Node {
4.4467 + BranchConn() {};
4.4468 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4469 + return next.match(matcher, i, seq);
4.4470 + }
4.4471 + boolean study(TreeInfo info) {
4.4472 + return info.deterministic;
4.4473 + }
4.4474 + }
4.4475 +
4.4476 + /**
4.4477 + * Handles the branching of alternations. Note this is also used for
4.4478 + * the ? quantifier to branch between the case where it matches once
4.4479 + * and where it does not occur.
4.4480 + */
4.4481 + static final class Branch extends Node {
4.4482 + Node[] atoms = new Node[2];
4.4483 + int size = 2;
4.4484 + Node conn;
4.4485 + Branch(Node first, Node second, Node branchConn) {
4.4486 + conn = branchConn;
4.4487 + atoms[0] = first;
4.4488 + atoms[1] = second;
4.4489 + }
4.4490 +
4.4491 + void add(Node node) {
4.4492 + if (size >= atoms.length) {
4.4493 + Node[] tmp = new Node[atoms.length*2];
4.4494 + System.arraycopy(atoms, 0, tmp, 0, atoms.length);
4.4495 + atoms = tmp;
4.4496 + }
4.4497 + atoms[size++] = node;
4.4498 + }
4.4499 +
4.4500 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4501 + for (int n = 0; n < size; n++) {
4.4502 + if (atoms[n] == null) {
4.4503 + if (conn.next.match(matcher, i, seq))
4.4504 + return true;
4.4505 + } else if (atoms[n].match(matcher, i, seq)) {
4.4506 + return true;
4.4507 + }
4.4508 + }
4.4509 + return false;
4.4510 + }
4.4511 +
4.4512 + boolean study(TreeInfo info) {
4.4513 + int minL = info.minLength;
4.4514 + int maxL = info.maxLength;
4.4515 + boolean maxV = info.maxValid;
4.4516 +
4.4517 + int minL2 = Integer.MAX_VALUE; //arbitrary large enough num
4.4518 + int maxL2 = -1;
4.4519 + for (int n = 0; n < size; n++) {
4.4520 + info.reset();
4.4521 + if (atoms[n] != null)
4.4522 + atoms[n].study(info);
4.4523 + minL2 = Math.min(minL2, info.minLength);
4.4524 + maxL2 = Math.max(maxL2, info.maxLength);
4.4525 + maxV = (maxV & info.maxValid);
4.4526 + }
4.4527 +
4.4528 + minL += minL2;
4.4529 + maxL += maxL2;
4.4530 +
4.4531 + info.reset();
4.4532 + conn.next.study(info);
4.4533 +
4.4534 + info.minLength += minL;
4.4535 + info.maxLength += maxL;
4.4536 + info.maxValid &= maxV;
4.4537 + info.deterministic = false;
4.4538 + return false;
4.4539 + }
4.4540 + }
4.4541 +
4.4542 + /**
4.4543 + * The GroupHead saves the location where the group begins in the locals
4.4544 + * and restores them when the match is done.
4.4545 + *
4.4546 + * The matchRef is used when a reference to this group is accessed later
4.4547 + * in the expression. The locals will have a negative value in them to
4.4548 + * indicate that we do not want to unset the group if the reference
4.4549 + * doesn't match.
4.4550 + */
4.4551 + static final class GroupHead extends Node {
4.4552 + int localIndex;
4.4553 + GroupHead(int localCount) {
4.4554 + localIndex = localCount;
4.4555 + }
4.4556 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4557 + int save = matcher.locals[localIndex];
4.4558 + matcher.locals[localIndex] = i;
4.4559 + boolean ret = next.match(matcher, i, seq);
4.4560 + matcher.locals[localIndex] = save;
4.4561 + return ret;
4.4562 + }
4.4563 + boolean matchRef(Matcher matcher, int i, CharSequence seq) {
4.4564 + int save = matcher.locals[localIndex];
4.4565 + matcher.locals[localIndex] = ~i; // HACK
4.4566 + boolean ret = next.match(matcher, i, seq);
4.4567 + matcher.locals[localIndex] = save;
4.4568 + return ret;
4.4569 + }
4.4570 + }
4.4571 +
4.4572 + /**
4.4573 + * Recursive reference to a group in the regular expression. It calls
4.4574 + * matchRef because if the reference fails to match we would not unset
4.4575 + * the group.
4.4576 + */
4.4577 + static final class GroupRef extends Node {
4.4578 + GroupHead head;
4.4579 + GroupRef(GroupHead head) {
4.4580 + this.head = head;
4.4581 + }
4.4582 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4583 + return head.matchRef(matcher, i, seq)
4.4584 + && next.match(matcher, matcher.last, seq);
4.4585 + }
4.4586 + boolean study(TreeInfo info) {
4.4587 + info.maxValid = false;
4.4588 + info.deterministic = false;
4.4589 + return next.study(info);
4.4590 + }
4.4591 + }
4.4592 +
4.4593 + /**
4.4594 + * The GroupTail handles the setting of group beginning and ending
4.4595 + * locations when groups are successfully matched. It must also be able to
4.4596 + * unset groups that have to be backed off of.
4.4597 + *
4.4598 + * The GroupTail node is also used when a previous group is referenced,
4.4599 + * and in that case no group information needs to be set.
4.4600 + */
4.4601 + static final class GroupTail extends Node {
4.4602 + int localIndex;
4.4603 + int groupIndex;
4.4604 + GroupTail(int localCount, int groupCount) {
4.4605 + localIndex = localCount;
4.4606 + groupIndex = groupCount + groupCount;
4.4607 + }
4.4608 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4609 + int tmp = matcher.locals[localIndex];
4.4610 + if (tmp >= 0) { // This is the normal group case.
4.4611 + // Save the group so we can unset it if it
4.4612 + // backs off of a match.
4.4613 + int groupStart = matcher.groups[groupIndex];
4.4614 + int groupEnd = matcher.groups[groupIndex+1];
4.4615 +
4.4616 + matcher.groups[groupIndex] = tmp;
4.4617 + matcher.groups[groupIndex+1] = i;
4.4618 + if (next.match(matcher, i, seq)) {
4.4619 + return true;
4.4620 + }
4.4621 + matcher.groups[groupIndex] = groupStart;
4.4622 + matcher.groups[groupIndex+1] = groupEnd;
4.4623 + return false;
4.4624 + } else {
4.4625 + // This is a group reference case. We don't need to save any
4.4626 + // group info because it isn't really a group.
4.4627 + matcher.last = i;
4.4628 + return true;
4.4629 + }
4.4630 + }
4.4631 + }
4.4632 +
4.4633 + /**
4.4634 + * This sets up a loop to handle a recursive quantifier structure.
4.4635 + */
4.4636 + static final class Prolog extends Node {
4.4637 + Loop loop;
4.4638 + Prolog(Loop loop) {
4.4639 + this.loop = loop;
4.4640 + }
4.4641 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4642 + return loop.matchInit(matcher, i, seq);
4.4643 + }
4.4644 + boolean study(TreeInfo info) {
4.4645 + return loop.study(info);
4.4646 + }
4.4647 + }
4.4648 +
4.4649 + /**
4.4650 + * Handles the repetition count for a greedy Curly. The matchInit
4.4651 + * is called from the Prolog to save the index of where the group
4.4652 + * beginning is stored. A zero length group check occurs in the
4.4653 + * normal match but is skipped in the matchInit.
4.4654 + */
4.4655 + static class Loop extends Node {
4.4656 + Node body;
4.4657 + int countIndex; // local count index in matcher locals
4.4658 + int beginIndex; // group beginning index
4.4659 + int cmin, cmax;
4.4660 + Loop(int countIndex, int beginIndex) {
4.4661 + this.countIndex = countIndex;
4.4662 + this.beginIndex = beginIndex;
4.4663 + }
4.4664 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4665 + // Avoid infinite loop in zero-length case.
4.4666 + if (i > matcher.locals[beginIndex]) {
4.4667 + int count = matcher.locals[countIndex];
4.4668 +
4.4669 + // This block is for before we reach the minimum
4.4670 + // iterations required for the loop to match
4.4671 + if (count < cmin) {
4.4672 + matcher.locals[countIndex] = count + 1;
4.4673 + boolean b = body.match(matcher, i, seq);
4.4674 + // If match failed we must backtrack, so
4.4675 + // the loop count should NOT be incremented
4.4676 + if (!b)
4.4677 + matcher.locals[countIndex] = count;
4.4678 + // Return success or failure since we are under
4.4679 + // minimum
4.4680 + return b;
4.4681 + }
4.4682 + // This block is for after we have the minimum
4.4683 + // iterations required for the loop to match
4.4684 + if (count < cmax) {
4.4685 + matcher.locals[countIndex] = count + 1;
4.4686 + boolean b = body.match(matcher, i, seq);
4.4687 + // If match failed we must backtrack, so
4.4688 + // the loop count should NOT be incremented
4.4689 + if (!b)
4.4690 + matcher.locals[countIndex] = count;
4.4691 + else
4.4692 + return true;
4.4693 + }
4.4694 + }
4.4695 + return next.match(matcher, i, seq);
4.4696 + }
4.4697 + boolean matchInit(Matcher matcher, int i, CharSequence seq) {
4.4698 + int save = matcher.locals[countIndex];
4.4699 + boolean ret = false;
4.4700 + if (0 < cmin) {
4.4701 + matcher.locals[countIndex] = 1;
4.4702 + ret = body.match(matcher, i, seq);
4.4703 + } else if (0 < cmax) {
4.4704 + matcher.locals[countIndex] = 1;
4.4705 + ret = body.match(matcher, i, seq);
4.4706 + if (ret == false)
4.4707 + ret = next.match(matcher, i, seq);
4.4708 + } else {
4.4709 + ret = next.match(matcher, i, seq);
4.4710 + }
4.4711 + matcher.locals[countIndex] = save;
4.4712 + return ret;
4.4713 + }
4.4714 + boolean study(TreeInfo info) {
4.4715 + info.maxValid = false;
4.4716 + info.deterministic = false;
4.4717 + return false;
4.4718 + }
4.4719 + }
4.4720 +
4.4721 + /**
4.4722 + * Handles the repetition count for a reluctant Curly. The matchInit
4.4723 + * is called from the Prolog to save the index of where the group
4.4724 + * beginning is stored. A zero length group check occurs in the
4.4725 + * normal match but is skipped in the matchInit.
4.4726 + */
4.4727 + static final class LazyLoop extends Loop {
4.4728 + LazyLoop(int countIndex, int beginIndex) {
4.4729 + super(countIndex, beginIndex);
4.4730 + }
4.4731 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4732 + // Check for zero length group
4.4733 + if (i > matcher.locals[beginIndex]) {
4.4734 + int count = matcher.locals[countIndex];
4.4735 + if (count < cmin) {
4.4736 + matcher.locals[countIndex] = count + 1;
4.4737 + boolean result = body.match(matcher, i, seq);
4.4738 + // If match failed we must backtrack, so
4.4739 + // the loop count should NOT be incremented
4.4740 + if (!result)
4.4741 + matcher.locals[countIndex] = count;
4.4742 + return result;
4.4743 + }
4.4744 + if (next.match(matcher, i, seq))
4.4745 + return true;
4.4746 + if (count < cmax) {
4.4747 + matcher.locals[countIndex] = count + 1;
4.4748 + boolean result = body.match(matcher, i, seq);
4.4749 + // If match failed we must backtrack, so
4.4750 + // the loop count should NOT be incremented
4.4751 + if (!result)
4.4752 + matcher.locals[countIndex] = count;
4.4753 + return result;
4.4754 + }
4.4755 + return false;
4.4756 + }
4.4757 + return next.match(matcher, i, seq);
4.4758 + }
4.4759 + boolean matchInit(Matcher matcher, int i, CharSequence seq) {
4.4760 + int save = matcher.locals[countIndex];
4.4761 + boolean ret = false;
4.4762 + if (0 < cmin) {
4.4763 + matcher.locals[countIndex] = 1;
4.4764 + ret = body.match(matcher, i, seq);
4.4765 + } else if (next.match(matcher, i, seq)) {
4.4766 + ret = true;
4.4767 + } else if (0 < cmax) {
4.4768 + matcher.locals[countIndex] = 1;
4.4769 + ret = body.match(matcher, i, seq);
4.4770 + }
4.4771 + matcher.locals[countIndex] = save;
4.4772 + return ret;
4.4773 + }
4.4774 + boolean study(TreeInfo info) {
4.4775 + info.maxValid = false;
4.4776 + info.deterministic = false;
4.4777 + return false;
4.4778 + }
4.4779 + }
4.4780 +
4.4781 + /**
4.4782 + * Refers to a group in the regular expression. Attempts to match
4.4783 + * whatever the group referred to last matched.
4.4784 + */
4.4785 + static class BackRef extends Node {
4.4786 + int groupIndex;
4.4787 + BackRef(int groupCount) {
4.4788 + super();
4.4789 + groupIndex = groupCount + groupCount;
4.4790 + }
4.4791 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4792 + int j = matcher.groups[groupIndex];
4.4793 + int k = matcher.groups[groupIndex+1];
4.4794 +
4.4795 + int groupSize = k - j;
4.4796 +
4.4797 + // If the referenced group didn't match, neither can this
4.4798 + if (j < 0)
4.4799 + return false;
4.4800 +
4.4801 + // If there isn't enough input left no match
4.4802 + if (i + groupSize > matcher.to) {
4.4803 + matcher.hitEnd = true;
4.4804 + return false;
4.4805 + }
4.4806 +
4.4807 + // Check each new char to make sure it matches what the group
4.4808 + // referenced matched last time around
4.4809 + for (int index=0; index<groupSize; index++)
4.4810 + if (seq.charAt(i+index) != seq.charAt(j+index))
4.4811 + return false;
4.4812 +
4.4813 + return next.match(matcher, i+groupSize, seq);
4.4814 + }
4.4815 + boolean study(TreeInfo info) {
4.4816 + info.maxValid = false;
4.4817 + return next.study(info);
4.4818 + }
4.4819 + }
4.4820 +
4.4821 + static class CIBackRef extends Node {
4.4822 + int groupIndex;
4.4823 + boolean doUnicodeCase;
4.4824 + CIBackRef(int groupCount, boolean doUnicodeCase) {
4.4825 + super();
4.4826 + groupIndex = groupCount + groupCount;
4.4827 + this.doUnicodeCase = doUnicodeCase;
4.4828 + }
4.4829 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4830 + int j = matcher.groups[groupIndex];
4.4831 + int k = matcher.groups[groupIndex+1];
4.4832 +
4.4833 + int groupSize = k - j;
4.4834 +
4.4835 + // If the referenced group didn't match, neither can this
4.4836 + if (j < 0)
4.4837 + return false;
4.4838 +
4.4839 + // If there isn't enough input left no match
4.4840 + if (i + groupSize > matcher.to) {
4.4841 + matcher.hitEnd = true;
4.4842 + return false;
4.4843 + }
4.4844 +
4.4845 + // Check each new char to make sure it matches what the group
4.4846 + // referenced matched last time around
4.4847 + int x = i;
4.4848 + for (int index=0; index<groupSize; index++) {
4.4849 + int c1 = Character.codePointAt(seq, x);
4.4850 + int c2 = Character.codePointAt(seq, j);
4.4851 + if (c1 != c2) {
4.4852 + if (doUnicodeCase) {
4.4853 + int cc1 = Character.toUpperCase(c1);
4.4854 + int cc2 = Character.toUpperCase(c2);
4.4855 + if (cc1 != cc2 &&
4.4856 + Character.toLowerCase(cc1) !=
4.4857 + Character.toLowerCase(cc2))
4.4858 + return false;
4.4859 + } else {
4.4860 + if (ASCII.toLower(c1) != ASCII.toLower(c2))
4.4861 + return false;
4.4862 + }
4.4863 + }
4.4864 + x += Character.charCount(c1);
4.4865 + j += Character.charCount(c2);
4.4866 + }
4.4867 +
4.4868 + return next.match(matcher, i+groupSize, seq);
4.4869 + }
4.4870 + boolean study(TreeInfo info) {
4.4871 + info.maxValid = false;
4.4872 + return next.study(info);
4.4873 + }
4.4874 + }
4.4875 +
4.4876 + /**
4.4877 + * Searches until the next instance of its atom. This is useful for
4.4878 + * finding the atom efficiently without passing an instance of it
4.4879 + * (greedy problem) and without a lot of wasted search time (reluctant
4.4880 + * problem).
4.4881 + */
4.4882 + static final class First extends Node {
4.4883 + Node atom;
4.4884 + First(Node node) {
4.4885 + this.atom = BnM.optimize(node);
4.4886 + }
4.4887 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4888 + if (atom instanceof BnM) {
4.4889 + return atom.match(matcher, i, seq)
4.4890 + && next.match(matcher, matcher.last, seq);
4.4891 + }
4.4892 + for (;;) {
4.4893 + if (i > matcher.to) {
4.4894 + matcher.hitEnd = true;
4.4895 + return false;
4.4896 + }
4.4897 + if (atom.match(matcher, i, seq)) {
4.4898 + return next.match(matcher, matcher.last, seq);
4.4899 + }
4.4900 + i += countChars(seq, i, 1);
4.4901 + matcher.first++;
4.4902 + }
4.4903 + }
4.4904 + boolean study(TreeInfo info) {
4.4905 + atom.study(info);
4.4906 + info.maxValid = false;
4.4907 + info.deterministic = false;
4.4908 + return next.study(info);
4.4909 + }
4.4910 + }
4.4911 +
4.4912 + static final class Conditional extends Node {
4.4913 + Node cond, yes, not;
4.4914 + Conditional(Node cond, Node yes, Node not) {
4.4915 + this.cond = cond;
4.4916 + this.yes = yes;
4.4917 + this.not = not;
4.4918 + }
4.4919 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4920 + if (cond.match(matcher, i, seq)) {
4.4921 + return yes.match(matcher, i, seq);
4.4922 + } else {
4.4923 + return not.match(matcher, i, seq);
4.4924 + }
4.4925 + }
4.4926 + boolean study(TreeInfo info) {
4.4927 + int minL = info.minLength;
4.4928 + int maxL = info.maxLength;
4.4929 + boolean maxV = info.maxValid;
4.4930 + info.reset();
4.4931 + yes.study(info);
4.4932 +
4.4933 + int minL2 = info.minLength;
4.4934 + int maxL2 = info.maxLength;
4.4935 + boolean maxV2 = info.maxValid;
4.4936 + info.reset();
4.4937 + not.study(info);
4.4938 +
4.4939 + info.minLength = minL + Math.min(minL2, info.minLength);
4.4940 + info.maxLength = maxL + Math.max(maxL2, info.maxLength);
4.4941 + info.maxValid = (maxV & maxV2 & info.maxValid);
4.4942 + info.deterministic = false;
4.4943 + return next.study(info);
4.4944 + }
4.4945 + }
4.4946 +
4.4947 + /**
4.4948 + * Zero width positive lookahead.
4.4949 + */
4.4950 + static final class Pos extends Node {
4.4951 + Node cond;
4.4952 + Pos(Node cond) {
4.4953 + this.cond = cond;
4.4954 + }
4.4955 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4956 + int savedTo = matcher.to;
4.4957 + boolean conditionMatched = false;
4.4958 +
4.4959 + // Relax transparent region boundaries for lookahead
4.4960 + if (matcher.transparentBounds)
4.4961 + matcher.to = matcher.getTextLength();
4.4962 + try {
4.4963 + conditionMatched = cond.match(matcher, i, seq);
4.4964 + } finally {
4.4965 + // Reinstate region boundaries
4.4966 + matcher.to = savedTo;
4.4967 + }
4.4968 + return conditionMatched && next.match(matcher, i, seq);
4.4969 + }
4.4970 + }
4.4971 +
4.4972 + /**
4.4973 + * Zero width negative lookahead.
4.4974 + */
4.4975 + static final class Neg extends Node {
4.4976 + Node cond;
4.4977 + Neg(Node cond) {
4.4978 + this.cond = cond;
4.4979 + }
4.4980 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.4981 + int savedTo = matcher.to;
4.4982 + boolean conditionMatched = false;
4.4983 +
4.4984 + // Relax transparent region boundaries for lookahead
4.4985 + if (matcher.transparentBounds)
4.4986 + matcher.to = matcher.getTextLength();
4.4987 + try {
4.4988 + if (i < matcher.to) {
4.4989 + conditionMatched = !cond.match(matcher, i, seq);
4.4990 + } else {
4.4991 + // If a negative lookahead succeeds then more input
4.4992 + // could cause it to fail!
4.4993 + matcher.requireEnd = true;
4.4994 + conditionMatched = !cond.match(matcher, i, seq);
4.4995 + }
4.4996 + } finally {
4.4997 + // Reinstate region boundaries
4.4998 + matcher.to = savedTo;
4.4999 + }
4.5000 + return conditionMatched && next.match(matcher, i, seq);
4.5001 + }
4.5002 + }
4.5003 +
4.5004 + /**
4.5005 + * For use with lookbehinds; matches the position where the lookbehind
4.5006 + * was encountered.
4.5007 + */
4.5008 + static Node lookbehindEnd = new Node() {
4.5009 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.5010 + return i == matcher.lookbehindTo;
4.5011 + }
4.5012 + };
4.5013 +
4.5014 + /**
4.5015 + * Zero width positive lookbehind.
4.5016 + */
4.5017 + static class Behind extends Node {
4.5018 + Node cond;
4.5019 + int rmax, rmin;
4.5020 + Behind(Node cond, int rmax, int rmin) {
4.5021 + this.cond = cond;
4.5022 + this.rmax = rmax;
4.5023 + this.rmin = rmin;
4.5024 + }
4.5025 +
4.5026 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.5027 + int savedFrom = matcher.from;
4.5028 + boolean conditionMatched = false;
4.5029 + int startIndex = (!matcher.transparentBounds) ?
4.5030 + matcher.from : 0;
4.5031 + int from = Math.max(i - rmax, startIndex);
4.5032 + // Set end boundary
4.5033 + int savedLBT = matcher.lookbehindTo;
4.5034 + matcher.lookbehindTo = i;
4.5035 + // Relax transparent region boundaries for lookbehind
4.5036 + if (matcher.transparentBounds)
4.5037 + matcher.from = 0;
4.5038 + for (int j = i - rmin; !conditionMatched && j >= from; j--) {
4.5039 + conditionMatched = cond.match(matcher, j, seq);
4.5040 + }
4.5041 + matcher.from = savedFrom;
4.5042 + matcher.lookbehindTo = savedLBT;
4.5043 + return conditionMatched && next.match(matcher, i, seq);
4.5044 + }
4.5045 + }
4.5046 +
4.5047 + /**
4.5048 + * Zero width positive lookbehind, including supplementary
4.5049 + * characters or unpaired surrogates.
4.5050 + */
4.5051 + static final class BehindS extends Behind {
4.5052 + BehindS(Node cond, int rmax, int rmin) {
4.5053 + super(cond, rmax, rmin);
4.5054 + }
4.5055 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.5056 + int rmaxChars = countChars(seq, i, -rmax);
4.5057 + int rminChars = countChars(seq, i, -rmin);
4.5058 + int savedFrom = matcher.from;
4.5059 + int startIndex = (!matcher.transparentBounds) ?
4.5060 + matcher.from : 0;
4.5061 + boolean conditionMatched = false;
4.5062 + int from = Math.max(i - rmaxChars, startIndex);
4.5063 + // Set end boundary
4.5064 + int savedLBT = matcher.lookbehindTo;
4.5065 + matcher.lookbehindTo = i;
4.5066 + // Relax transparent region boundaries for lookbehind
4.5067 + if (matcher.transparentBounds)
4.5068 + matcher.from = 0;
4.5069 +
4.5070 + for (int j = i - rminChars;
4.5071 + !conditionMatched && j >= from;
4.5072 + j -= j>from ? countChars(seq, j, -1) : 1) {
4.5073 + conditionMatched = cond.match(matcher, j, seq);
4.5074 + }
4.5075 + matcher.from = savedFrom;
4.5076 + matcher.lookbehindTo = savedLBT;
4.5077 + return conditionMatched && next.match(matcher, i, seq);
4.5078 + }
4.5079 + }
4.5080 +
4.5081 + /**
4.5082 + * Zero width negative lookbehind.
4.5083 + */
4.5084 + static class NotBehind extends Node {
4.5085 + Node cond;
4.5086 + int rmax, rmin;
4.5087 + NotBehind(Node cond, int rmax, int rmin) {
4.5088 + this.cond = cond;
4.5089 + this.rmax = rmax;
4.5090 + this.rmin = rmin;
4.5091 + }
4.5092 +
4.5093 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.5094 + int savedLBT = matcher.lookbehindTo;
4.5095 + int savedFrom = matcher.from;
4.5096 + boolean conditionMatched = false;
4.5097 + int startIndex = (!matcher.transparentBounds) ?
4.5098 + matcher.from : 0;
4.5099 + int from = Math.max(i - rmax, startIndex);
4.5100 + matcher.lookbehindTo = i;
4.5101 + // Relax transparent region boundaries for lookbehind
4.5102 + if (matcher.transparentBounds)
4.5103 + matcher.from = 0;
4.5104 + for (int j = i - rmin; !conditionMatched && j >= from; j--) {
4.5105 + conditionMatched = cond.match(matcher, j, seq);
4.5106 + }
4.5107 + // Reinstate region boundaries
4.5108 + matcher.from = savedFrom;
4.5109 + matcher.lookbehindTo = savedLBT;
4.5110 + return !conditionMatched && next.match(matcher, i, seq);
4.5111 + }
4.5112 + }
4.5113 +
4.5114 + /**
4.5115 + * Zero width negative lookbehind, including supplementary
4.5116 + * characters or unpaired surrogates.
4.5117 + */
4.5118 + static final class NotBehindS extends NotBehind {
4.5119 + NotBehindS(Node cond, int rmax, int rmin) {
4.5120 + super(cond, rmax, rmin);
4.5121 + }
4.5122 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.5123 + int rmaxChars = countChars(seq, i, -rmax);
4.5124 + int rminChars = countChars(seq, i, -rmin);
4.5125 + int savedFrom = matcher.from;
4.5126 + int savedLBT = matcher.lookbehindTo;
4.5127 + boolean conditionMatched = false;
4.5128 + int startIndex = (!matcher.transparentBounds) ?
4.5129 + matcher.from : 0;
4.5130 + int from = Math.max(i - rmaxChars, startIndex);
4.5131 + matcher.lookbehindTo = i;
4.5132 + // Relax transparent region boundaries for lookbehind
4.5133 + if (matcher.transparentBounds)
4.5134 + matcher.from = 0;
4.5135 + for (int j = i - rminChars;
4.5136 + !conditionMatched && j >= from;
4.5137 + j -= j>from ? countChars(seq, j, -1) : 1) {
4.5138 + conditionMatched = cond.match(matcher, j, seq);
4.5139 + }
4.5140 + //Reinstate region boundaries
4.5141 + matcher.from = savedFrom;
4.5142 + matcher.lookbehindTo = savedLBT;
4.5143 + return !conditionMatched && next.match(matcher, i, seq);
4.5144 + }
4.5145 + }
4.5146 +
4.5147 + /**
4.5148 + * Returns the set union of two CharProperty nodes.
4.5149 + */
4.5150 + private static CharProperty union(final CharProperty lhs,
4.5151 + final CharProperty rhs) {
4.5152 + return new CharProperty() {
4.5153 + boolean isSatisfiedBy(int ch) {
4.5154 + return lhs.isSatisfiedBy(ch) || rhs.isSatisfiedBy(ch);}};
4.5155 + }
4.5156 +
4.5157 + /**
4.5158 + * Returns the set intersection of two CharProperty nodes.
4.5159 + */
4.5160 + private static CharProperty intersection(final CharProperty lhs,
4.5161 + final CharProperty rhs) {
4.5162 + return new CharProperty() {
4.5163 + boolean isSatisfiedBy(int ch) {
4.5164 + return lhs.isSatisfiedBy(ch) && rhs.isSatisfiedBy(ch);}};
4.5165 + }
4.5166 +
4.5167 + /**
4.5168 + * Returns the set difference of two CharProperty nodes.
4.5169 + */
4.5170 + private static CharProperty setDifference(final CharProperty lhs,
4.5171 + final CharProperty rhs) {
4.5172 + return new CharProperty() {
4.5173 + boolean isSatisfiedBy(int ch) {
4.5174 + return ! rhs.isSatisfiedBy(ch) && lhs.isSatisfiedBy(ch);}};
4.5175 + }
4.5176 +
4.5177 + /**
4.5178 + * Handles word boundaries. Includes a field to allow this one class to
4.5179 + * deal with the different types of word boundaries we can match. The word
4.5180 + * characters include underscores, letters, and digits. Non spacing marks
4.5181 + * can are also part of a word if they have a base character, otherwise
4.5182 + * they are ignored for purposes of finding word boundaries.
4.5183 + */
4.5184 + static final class Bound extends Node {
4.5185 + static int LEFT = 0x1;
4.5186 + static int RIGHT= 0x2;
4.5187 + static int BOTH = 0x3;
4.5188 + static int NONE = 0x4;
4.5189 + int type;
4.5190 + boolean useUWORD;
4.5191 + Bound(int n, boolean useUWORD) {
4.5192 + type = n;
4.5193 + this.useUWORD = useUWORD;
4.5194 + }
4.5195 +
4.5196 + boolean isWord(int ch) {
4.5197 + return useUWORD ? UnicodeProp.WORD.is(ch)
4.5198 + : (ch == '_' || Character.isLetterOrDigit(ch));
4.5199 + }
4.5200 +
4.5201 + int check(Matcher matcher, int i, CharSequence seq) {
4.5202 + int ch;
4.5203 + boolean left = false;
4.5204 + int startIndex = matcher.from;
4.5205 + int endIndex = matcher.to;
4.5206 + if (matcher.transparentBounds) {
4.5207 + startIndex = 0;
4.5208 + endIndex = matcher.getTextLength();
4.5209 + }
4.5210 + if (i > startIndex) {
4.5211 + ch = Character.codePointBefore(seq, i);
4.5212 + left = (isWord(ch) ||
4.5213 + ((Character.getType(ch) == Character.NON_SPACING_MARK)
4.5214 + && hasBaseCharacter(matcher, i-1, seq)));
4.5215 + }
4.5216 + boolean right = false;
4.5217 + if (i < endIndex) {
4.5218 + ch = Character.codePointAt(seq, i);
4.5219 + right = (isWord(ch) ||
4.5220 + ((Character.getType(ch) == Character.NON_SPACING_MARK)
4.5221 + && hasBaseCharacter(matcher, i, seq)));
4.5222 + } else {
4.5223 + // Tried to access char past the end
4.5224 + matcher.hitEnd = true;
4.5225 + // The addition of another char could wreck a boundary
4.5226 + matcher.requireEnd = true;
4.5227 + }
4.5228 + return ((left ^ right) ? (right ? LEFT : RIGHT) : NONE);
4.5229 + }
4.5230 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.5231 + return (check(matcher, i, seq) & type) > 0
4.5232 + && next.match(matcher, i, seq);
4.5233 + }
4.5234 + }
4.5235 +
4.5236 + /**
4.5237 + * Non spacing marks only count as word characters in bounds calculations
4.5238 + * if they have a base character.
4.5239 + */
4.5240 + private static boolean hasBaseCharacter(Matcher matcher, int i,
4.5241 + CharSequence seq)
4.5242 + {
4.5243 + int start = (!matcher.transparentBounds) ?
4.5244 + matcher.from : 0;
4.5245 + for (int x=i; x >= start; x--) {
4.5246 + int ch = Character.codePointAt(seq, x);
4.5247 + if (Character.isLetterOrDigit(ch))
4.5248 + return true;
4.5249 + if (Character.getType(ch) == Character.NON_SPACING_MARK)
4.5250 + continue;
4.5251 + return false;
4.5252 + }
4.5253 + return false;
4.5254 + }
4.5255 +
4.5256 + /**
4.5257 + * Attempts to match a slice in the input using the Boyer-Moore string
4.5258 + * matching algorithm. The algorithm is based on the idea that the
4.5259 + * pattern can be shifted farther ahead in the search text if it is
4.5260 + * matched right to left.
4.5261 + * <p>
4.5262 + * The pattern is compared to the input one character at a time, from
4.5263 + * the rightmost character in the pattern to the left. If the characters
4.5264 + * all match the pattern has been found. If a character does not match,
4.5265 + * the pattern is shifted right a distance that is the maximum of two
4.5266 + * functions, the bad character shift and the good suffix shift. This
4.5267 + * shift moves the attempted match position through the input more
4.5268 + * quickly than a naive one position at a time check.
4.5269 + * <p>
4.5270 + * The bad character shift is based on the character from the text that
4.5271 + * did not match. If the character does not appear in the pattern, the
4.5272 + * pattern can be shifted completely beyond the bad character. If the
4.5273 + * character does occur in the pattern, the pattern can be shifted to
4.5274 + * line the pattern up with the next occurrence of that character.
4.5275 + * <p>
4.5276 + * The good suffix shift is based on the idea that some subset on the right
4.5277 + * side of the pattern has matched. When a bad character is found, the
4.5278 + * pattern can be shifted right by the pattern length if the subset does
4.5279 + * not occur again in pattern, or by the amount of distance to the
4.5280 + * next occurrence of the subset in the pattern.
4.5281 + *
4.5282 + * Boyer-Moore search methods adapted from code by Amy Yu.
4.5283 + */
4.5284 + static class BnM extends Node {
4.5285 + int[] buffer;
4.5286 + int[] lastOcc;
4.5287 + int[] optoSft;
4.5288 +
4.5289 + /**
4.5290 + * Pre calculates arrays needed to generate the bad character
4.5291 + * shift and the good suffix shift. Only the last seven bits
4.5292 + * are used to see if chars match; This keeps the tables small
4.5293 + * and covers the heavily used ASCII range, but occasionally
4.5294 + * results in an aliased match for the bad character shift.
4.5295 + */
4.5296 + static Node optimize(Node node) {
4.5297 + if (!(node instanceof Slice)) {
4.5298 + return node;
4.5299 + }
4.5300 +
4.5301 + int[] src = ((Slice) node).buffer;
4.5302 + int patternLength = src.length;
4.5303 + // The BM algorithm requires a bit of overhead;
4.5304 + // If the pattern is short don't use it, since
4.5305 + // a shift larger than the pattern length cannot
4.5306 + // be used anyway.
4.5307 + if (patternLength < 4) {
4.5308 + return node;
4.5309 + }
4.5310 + int i, j, k;
4.5311 + int[] lastOcc = new int[128];
4.5312 + int[] optoSft = new int[patternLength];
4.5313 + // Precalculate part of the bad character shift
4.5314 + // It is a table for where in the pattern each
4.5315 + // lower 7-bit value occurs
4.5316 + for (i = 0; i < patternLength; i++) {
4.5317 + lastOcc[src[i]&0x7F] = i + 1;
4.5318 + }
4.5319 + // Precalculate the good suffix shift
4.5320 + // i is the shift amount being considered
4.5321 +NEXT: for (i = patternLength; i > 0; i--) {
4.5322 + // j is the beginning index of suffix being considered
4.5323 + for (j = patternLength - 1; j >= i; j--) {
4.5324 + // Testing for good suffix
4.5325 + if (src[j] == src[j-i]) {
4.5326 + // src[j..len] is a good suffix
4.5327 + optoSft[j-1] = i;
4.5328 + } else {
4.5329 + // No match. The array has already been
4.5330 + // filled up with correct values before.
4.5331 + continue NEXT;
4.5332 + }
4.5333 + }
4.5334 + // This fills up the remaining of optoSft
4.5335 + // any suffix can not have larger shift amount
4.5336 + // then its sub-suffix. Why???
4.5337 + while (j > 0) {
4.5338 + optoSft[--j] = i;
4.5339 + }
4.5340 + }
4.5341 + // Set the guard value because of unicode compression
4.5342 + optoSft[patternLength-1] = 1;
4.5343 + if (node instanceof SliceS)
4.5344 + return new BnMS(src, lastOcc, optoSft, node.next);
4.5345 + return new BnM(src, lastOcc, optoSft, node.next);
4.5346 + }
4.5347 + BnM(int[] src, int[] lastOcc, int[] optoSft, Node next) {
4.5348 + this.buffer = src;
4.5349 + this.lastOcc = lastOcc;
4.5350 + this.optoSft = optoSft;
4.5351 + this.next = next;
4.5352 + }
4.5353 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.5354 + int[] src = buffer;
4.5355 + int patternLength = src.length;
4.5356 + int last = matcher.to - patternLength;
4.5357 +
4.5358 + // Loop over all possible match positions in text
4.5359 +NEXT: while (i <= last) {
4.5360 + // Loop over pattern from right to left
4.5361 + for (int j = patternLength - 1; j >= 0; j--) {
4.5362 + int ch = seq.charAt(i+j);
4.5363 + if (ch != src[j]) {
4.5364 + // Shift search to the right by the maximum of the
4.5365 + // bad character shift and the good suffix shift
4.5366 + i += Math.max(j + 1 - lastOcc[ch&0x7F], optoSft[j]);
4.5367 + continue NEXT;
4.5368 + }
4.5369 + }
4.5370 + // Entire pattern matched starting at i
4.5371 + matcher.first = i;
4.5372 + boolean ret = next.match(matcher, i + patternLength, seq);
4.5373 + if (ret) {
4.5374 + matcher.first = i;
4.5375 + matcher.groups[0] = matcher.first;
4.5376 + matcher.groups[1] = matcher.last;
4.5377 + return true;
4.5378 + }
4.5379 + i++;
4.5380 + }
4.5381 + // BnM is only used as the leading node in the unanchored case,
4.5382 + // and it replaced its Start() which always searches to the end
4.5383 + // if it doesn't find what it's looking for, so hitEnd is true.
4.5384 + matcher.hitEnd = true;
4.5385 + return false;
4.5386 + }
4.5387 + boolean study(TreeInfo info) {
4.5388 + info.minLength += buffer.length;
4.5389 + info.maxValid = false;
4.5390 + return next.study(info);
4.5391 + }
4.5392 + }
4.5393 +
4.5394 + /**
4.5395 + * Supplementary support version of BnM(). Unpaired surrogates are
4.5396 + * also handled by this class.
4.5397 + */
4.5398 + static final class BnMS extends BnM {
4.5399 + int lengthInChars;
4.5400 +
4.5401 + BnMS(int[] src, int[] lastOcc, int[] optoSft, Node next) {
4.5402 + super(src, lastOcc, optoSft, next);
4.5403 + for (int x = 0; x < buffer.length; x++) {
4.5404 + lengthInChars += Character.charCount(buffer[x]);
4.5405 + }
4.5406 + }
4.5407 + boolean match(Matcher matcher, int i, CharSequence seq) {
4.5408 + int[] src = buffer;
4.5409 + int patternLength = src.length;
4.5410 + int last = matcher.to - lengthInChars;
4.5411 +
4.5412 + // Loop over all possible match positions in text
4.5413 +NEXT: while (i <= last) {
4.5414 + // Loop over pattern from right to left
4.5415 + int ch;
4.5416 + for (int j = countChars(seq, i, patternLength), x = patternLength - 1;
4.5417 + j > 0; j -= Character.charCount(ch), x--) {
4.5418 + ch = Character.codePointBefore(seq, i+j);
4.5419 + if (ch != src[x]) {
4.5420 + // Shift search to the right by the maximum of the
4.5421 + // bad character shift and the good suffix shift
4.5422 + int n = Math.max(x + 1 - lastOcc[ch&0x7F], optoSft[x]);
4.5423 + i += countChars(seq, i, n);
4.5424 + continue NEXT;
4.5425 + }
4.5426 + }
4.5427 + // Entire pattern matched starting at i
4.5428 + matcher.first = i;
4.5429 + boolean ret = next.match(matcher, i + lengthInChars, seq);
4.5430 + if (ret) {
4.5431 + matcher.first = i;
4.5432 + matcher.groups[0] = matcher.first;
4.5433 + matcher.groups[1] = matcher.last;
4.5434 + return true;
4.5435 + }
4.5436 + i += countChars(seq, i, 1);
4.5437 + }
4.5438 + matcher.hitEnd = true;
4.5439 + return false;
4.5440 + }
4.5441 + }
4.5442 +
4.5443 +///////////////////////////////////////////////////////////////////////////////
4.5444 +///////////////////////////////////////////////////////////////////////////////
4.5445 +
4.5446 + /**
4.5447 + * This must be the very first initializer.
4.5448 + */
4.5449 + static Node accept = new Node();
4.5450 +
4.5451 + static Node lastAccept = new LastNode();
4.5452 +
4.5453 + private static class CharPropertyNames {
4.5454 +
4.5455 + static CharProperty charPropertyFor(String name) {
4.5456 + CharPropertyFactory m = map.get(name);
4.5457 + return m == null ? null : m.make();
4.5458 + }
4.5459 +
4.5460 + private static abstract class CharPropertyFactory {
4.5461 + abstract CharProperty make();
4.5462 + }
4.5463 +
4.5464 + private static void defCategory(String name,
4.5465 + final int typeMask) {
4.5466 + map.put(name, new CharPropertyFactory() {
4.5467 + CharProperty make() { return new Category(typeMask);}});
4.5468 + }
4.5469 +
4.5470 + private static void defRange(String name,
4.5471 + final int lower, final int upper) {
4.5472 + map.put(name, new CharPropertyFactory() {
4.5473 + CharProperty make() { return rangeFor(lower, upper);}});
4.5474 + }
4.5475 +
4.5476 + private static void defCtype(String name,
4.5477 + final int ctype) {
4.5478 + map.put(name, new CharPropertyFactory() {
4.5479 + CharProperty make() { return new Ctype(ctype);}});
4.5480 + }
4.5481 +
4.5482 + private static abstract class CloneableProperty
4.5483 + extends CharProperty implements Cloneable
4.5484 + {
4.5485 + public CloneableProperty clone() {
4.5486 + try {
4.5487 + return (CloneableProperty) super.clone();
4.5488 + } catch (CloneNotSupportedException e) {
4.5489 + throw new AssertionError(e);
4.5490 + }
4.5491 + }
4.5492 + }
4.5493 +
4.5494 + private static void defClone(String name,
4.5495 + final CloneableProperty p) {
4.5496 + map.put(name, new CharPropertyFactory() {
4.5497 + CharProperty make() { return p.clone();}});
4.5498 + }
4.5499 +
4.5500 + private static final HashMap<String, CharPropertyFactory> map
4.5501 + = new HashMap<>();
4.5502 +
4.5503 + static {
4.5504 + // Unicode character property aliases, defined in
4.5505 + // http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt
4.5506 + defCategory("Cn", 1<<Character.UNASSIGNED);
4.5507 + defCategory("Lu", 1<<Character.UPPERCASE_LETTER);
4.5508 + defCategory("Ll", 1<<Character.LOWERCASE_LETTER);
4.5509 + defCategory("Lt", 1<<Character.TITLECASE_LETTER);
4.5510 + defCategory("Lm", 1<<Character.MODIFIER_LETTER);
4.5511 + defCategory("Lo", 1<<Character.OTHER_LETTER);
4.5512 + defCategory("Mn", 1<<Character.NON_SPACING_MARK);
4.5513 + defCategory("Me", 1<<Character.ENCLOSING_MARK);
4.5514 + defCategory("Mc", 1<<Character.COMBINING_SPACING_MARK);
4.5515 + defCategory("Nd", 1<<Character.DECIMAL_DIGIT_NUMBER);
4.5516 + defCategory("Nl", 1<<Character.LETTER_NUMBER);
4.5517 + defCategory("No", 1<<Character.OTHER_NUMBER);
4.5518 + defCategory("Zs", 1<<Character.SPACE_SEPARATOR);
4.5519 + defCategory("Zl", 1<<Character.LINE_SEPARATOR);
4.5520 + defCategory("Zp", 1<<Character.PARAGRAPH_SEPARATOR);
4.5521 + defCategory("Cc", 1<<Character.CONTROL);
4.5522 + defCategory("Cf", 1<<Character.FORMAT);
4.5523 + defCategory("Co", 1<<Character.PRIVATE_USE);
4.5524 + defCategory("Cs", 1<<Character.SURROGATE);
4.5525 + defCategory("Pd", 1<<Character.DASH_PUNCTUATION);
4.5526 + defCategory("Ps", 1<<Character.START_PUNCTUATION);
4.5527 + defCategory("Pe", 1<<Character.END_PUNCTUATION);
4.5528 + defCategory("Pc", 1<<Character.CONNECTOR_PUNCTUATION);
4.5529 + defCategory("Po", 1<<Character.OTHER_PUNCTUATION);
4.5530 + defCategory("Sm", 1<<Character.MATH_SYMBOL);
4.5531 + defCategory("Sc", 1<<Character.CURRENCY_SYMBOL);
4.5532 + defCategory("Sk", 1<<Character.MODIFIER_SYMBOL);
4.5533 + defCategory("So", 1<<Character.OTHER_SYMBOL);
4.5534 + defCategory("Pi", 1<<Character.INITIAL_QUOTE_PUNCTUATION);
4.5535 + defCategory("Pf", 1<<Character.FINAL_QUOTE_PUNCTUATION);
4.5536 + defCategory("L", ((1<<Character.UPPERCASE_LETTER) |
4.5537 + (1<<Character.LOWERCASE_LETTER) |
4.5538 + (1<<Character.TITLECASE_LETTER) |
4.5539 + (1<<Character.MODIFIER_LETTER) |
4.5540 + (1<<Character.OTHER_LETTER)));
4.5541 + defCategory("M", ((1<<Character.NON_SPACING_MARK) |
4.5542 + (1<<Character.ENCLOSING_MARK) |
4.5543 + (1<<Character.COMBINING_SPACING_MARK)));
4.5544 + defCategory("N", ((1<<Character.DECIMAL_DIGIT_NUMBER) |
4.5545 + (1<<Character.LETTER_NUMBER) |
4.5546 + (1<<Character.OTHER_NUMBER)));
4.5547 + defCategory("Z", ((1<<Character.SPACE_SEPARATOR) |
4.5548 + (1<<Character.LINE_SEPARATOR) |
4.5549 + (1<<Character.PARAGRAPH_SEPARATOR)));
4.5550 + defCategory("C", ((1<<Character.CONTROL) |
4.5551 + (1<<Character.FORMAT) |
4.5552 + (1<<Character.PRIVATE_USE) |
4.5553 + (1<<Character.SURROGATE))); // Other
4.5554 + defCategory("P", ((1<<Character.DASH_PUNCTUATION) |
4.5555 + (1<<Character.START_PUNCTUATION) |
4.5556 + (1<<Character.END_PUNCTUATION) |
4.5557 + (1<<Character.CONNECTOR_PUNCTUATION) |
4.5558 + (1<<Character.OTHER_PUNCTUATION) |
4.5559 + (1<<Character.INITIAL_QUOTE_PUNCTUATION) |
4.5560 + (1<<Character.FINAL_QUOTE_PUNCTUATION)));
4.5561 + defCategory("S", ((1<<Character.MATH_SYMBOL) |
4.5562 + (1<<Character.CURRENCY_SYMBOL) |
4.5563 + (1<<Character.MODIFIER_SYMBOL) |
4.5564 + (1<<Character.OTHER_SYMBOL)));
4.5565 + defCategory("LC", ((1<<Character.UPPERCASE_LETTER) |
4.5566 + (1<<Character.LOWERCASE_LETTER) |
4.5567 + (1<<Character.TITLECASE_LETTER)));
4.5568 + defCategory("LD", ((1<<Character.UPPERCASE_LETTER) |
4.5569 + (1<<Character.LOWERCASE_LETTER) |
4.5570 + (1<<Character.TITLECASE_LETTER) |
4.5571 + (1<<Character.MODIFIER_LETTER) |
4.5572 + (1<<Character.OTHER_LETTER) |
4.5573 + (1<<Character.DECIMAL_DIGIT_NUMBER)));
4.5574 + defRange("L1", 0x00, 0xFF); // Latin-1
4.5575 + map.put("all", new CharPropertyFactory() {
4.5576 + CharProperty make() { return new All(); }});
4.5577 +
4.5578 + // Posix regular expression character classes, defined in
4.5579 + // http://www.unix.org/onlinepubs/009695399/basedefs/xbd_chap09.html
4.5580 + defRange("ASCII", 0x00, 0x7F); // ASCII
4.5581 + defCtype("Alnum", ASCII.ALNUM); // Alphanumeric characters
4.5582 + defCtype("Alpha", ASCII.ALPHA); // Alphabetic characters
4.5583 + defCtype("Blank", ASCII.BLANK); // Space and tab characters
4.5584 + defCtype("Cntrl", ASCII.CNTRL); // Control characters
4.5585 + defRange("Digit", '0', '9'); // Numeric characters
4.5586 + defCtype("Graph", ASCII.GRAPH); // printable and visible
4.5587 + defRange("Lower", 'a', 'z'); // Lower-case alphabetic
4.5588 + defRange("Print", 0x20, 0x7E); // Printable characters
4.5589 + defCtype("Punct", ASCII.PUNCT); // Punctuation characters
4.5590 + defCtype("Space", ASCII.SPACE); // Space characters
4.5591 + defRange("Upper", 'A', 'Z'); // Upper-case alphabetic
4.5592 + defCtype("XDigit",ASCII.XDIGIT); // hexadecimal digits
4.5593 +
4.5594 + // Java character properties, defined by methods in Character.java
4.5595 + defClone("javaLowerCase", new CloneableProperty() {
4.5596 + boolean isSatisfiedBy(int ch) {
4.5597 + return Character.isLowerCase(ch);}});
4.5598 + defClone("javaUpperCase", new CloneableProperty() {
4.5599 + boolean isSatisfiedBy(int ch) {
4.5600 + return Character.isUpperCase(ch);}});
4.5601 + defClone("javaAlphabetic", new CloneableProperty() {
4.5602 + boolean isSatisfiedBy(int ch) {
4.5603 + return Character.isAlphabetic(ch);}});
4.5604 + defClone("javaIdeographic", new CloneableProperty() {
4.5605 + boolean isSatisfiedBy(int ch) {
4.5606 + return Character.isIdeographic(ch);}});
4.5607 + defClone("javaTitleCase", new CloneableProperty() {
4.5608 + boolean isSatisfiedBy(int ch) {
4.5609 + return Character.isTitleCase(ch);}});
4.5610 + defClone("javaDigit", new CloneableProperty() {
4.5611 + boolean isSatisfiedBy(int ch) {
4.5612 + return Character.isDigit(ch);}});
4.5613 + defClone("javaDefined", new CloneableProperty() {
4.5614 + boolean isSatisfiedBy(int ch) {
4.5615 + return Character.isDefined(ch);}});
4.5616 + defClone("javaLetter", new CloneableProperty() {
4.5617 + boolean isSatisfiedBy(int ch) {
4.5618 + return Character.isLetter(ch);}});
4.5619 + defClone("javaLetterOrDigit", new CloneableProperty() {
4.5620 + boolean isSatisfiedBy(int ch) {
4.5621 + return Character.isLetterOrDigit(ch);}});
4.5622 + defClone("javaJavaIdentifierStart", new CloneableProperty() {
4.5623 + boolean isSatisfiedBy(int ch) {
4.5624 + return Character.isJavaIdentifierStart(ch);}});
4.5625 + defClone("javaJavaIdentifierPart", new CloneableProperty() {
4.5626 + boolean isSatisfiedBy(int ch) {
4.5627 + return Character.isJavaIdentifierPart(ch);}});
4.5628 + defClone("javaUnicodeIdentifierStart", new CloneableProperty() {
4.5629 + boolean isSatisfiedBy(int ch) {
4.5630 + return Character.isUnicodeIdentifierStart(ch);}});
4.5631 + defClone("javaUnicodeIdentifierPart", new CloneableProperty() {
4.5632 + boolean isSatisfiedBy(int ch) {
4.5633 + return Character.isUnicodeIdentifierPart(ch);}});
4.5634 + defClone("javaIdentifierIgnorable", new CloneableProperty() {
4.5635 + boolean isSatisfiedBy(int ch) {
4.5636 + return Character.isIdentifierIgnorable(ch);}});
4.5637 + defClone("javaSpaceChar", new CloneableProperty() {
4.5638 + boolean isSatisfiedBy(int ch) {
4.5639 + return Character.isSpaceChar(ch);}});
4.5640 + defClone("javaWhitespace", new CloneableProperty() {
4.5641 + boolean isSatisfiedBy(int ch) {
4.5642 + return Character.isWhitespace(ch);}});
4.5643 + defClone("javaISOControl", new CloneableProperty() {
4.5644 + boolean isSatisfiedBy(int ch) {
4.5645 + return Character.isISOControl(ch);}});
4.5646 + defClone("javaMirrored", new CloneableProperty() {
4.5647 + boolean isSatisfiedBy(int ch) {
4.5648 + return Character.isMirrored(ch);}});
4.5649 + }
4.5650 + }
4.5651 +}
5.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
5.2 +++ b/rt/emul/compact/src/main/java/java/util/regex/PatternSyntaxException.java Mon Oct 07 16:13:27 2013 +0200
5.3 @@ -0,0 +1,124 @@
5.4 +/*
5.5 + * Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
5.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5.7 + *
5.8 + * This code is free software; you can redistribute it and/or modify it
5.9 + * under the terms of the GNU General Public License version 2 only, as
5.10 + * published by the Free Software Foundation. Oracle designates this
5.11 + * particular file as subject to the "Classpath" exception as provided
5.12 + * by Oracle in the LICENSE file that accompanied this code.
5.13 + *
5.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
5.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
5.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
5.17 + * version 2 for more details (a copy is included in the LICENSE file that
5.18 + * accompanied this code).
5.19 + *
5.20 + * You should have received a copy of the GNU General Public License version
5.21 + * 2 along with this work; if not, write to the Free Software Foundation,
5.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
5.23 + *
5.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
5.25 + * or visit www.oracle.com if you need additional information or have any
5.26 + * questions.
5.27 + */
5.28 +
5.29 +package java.util.regex;
5.30 +
5.31 +import sun.security.action.GetPropertyAction;
5.32 +
5.33 +
5.34 +/**
5.35 + * Unchecked exception thrown to indicate a syntax error in a
5.36 + * regular-expression pattern.
5.37 + *
5.38 + * @author unascribed
5.39 + * @since 1.4
5.40 + * @spec JSR-51
5.41 + */
5.42 +
5.43 +public class PatternSyntaxException
5.44 + extends IllegalArgumentException
5.45 +{
5.46 + private static final long serialVersionUID = -3864639126226059218L;
5.47 +
5.48 + private final String desc;
5.49 + private final String pattern;
5.50 + private final int index;
5.51 +
5.52 + /**
5.53 + * Constructs a new instance of this class.
5.54 + *
5.55 + * @param desc
5.56 + * A description of the error
5.57 + *
5.58 + * @param regex
5.59 + * The erroneous pattern
5.60 + *
5.61 + * @param index
5.62 + * The approximate index in the pattern of the error,
5.63 + * or <tt>-1</tt> if the index is not known
5.64 + */
5.65 + public PatternSyntaxException(String desc, String regex, int index) {
5.66 + this.desc = desc;
5.67 + this.pattern = regex;
5.68 + this.index = index;
5.69 + }
5.70 +
5.71 + /**
5.72 + * Retrieves the error index.
5.73 + *
5.74 + * @return The approximate index in the pattern of the error,
5.75 + * or <tt>-1</tt> if the index is not known
5.76 + */
5.77 + public int getIndex() {
5.78 + return index;
5.79 + }
5.80 +
5.81 + /**
5.82 + * Retrieves the description of the error.
5.83 + *
5.84 + * @return The description of the error
5.85 + */
5.86 + public String getDescription() {
5.87 + return desc;
5.88 + }
5.89 +
5.90 + /**
5.91 + * Retrieves the erroneous regular-expression pattern.
5.92 + *
5.93 + * @return The erroneous pattern
5.94 + */
5.95 + public String getPattern() {
5.96 + return pattern;
5.97 + }
5.98 +
5.99 + private static final String nl =
5.100 + java.security.AccessController
5.101 + .doPrivileged(new GetPropertyAction("line.separator"));
5.102 +
5.103 + /**
5.104 + * Returns a multi-line string containing the description of the syntax
5.105 + * error and its index, the erroneous regular-expression pattern, and a
5.106 + * visual indication of the error index within the pattern.
5.107 + *
5.108 + * @return The full detail message
5.109 + */
5.110 + public String getMessage() {
5.111 + StringBuffer sb = new StringBuffer();
5.112 + sb.append(desc);
5.113 + if (index >= 0) {
5.114 + sb.append(" near index ");
5.115 + sb.append(index);
5.116 + }
5.117 + sb.append(nl);
5.118 + sb.append(pattern);
5.119 + if (index >= 0) {
5.120 + sb.append(nl);
5.121 + for (int i = 0; i < index; i++) sb.append(' ');
5.122 + sb.append('^');
5.123 + }
5.124 + return sb.toString();
5.125 + }
5.126 +
5.127 +}
6.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
6.2 +++ b/rt/emul/compact/src/main/java/java/util/regex/UnicodeProp.java Mon Oct 07 16:13:27 2013 +0200
6.3 @@ -0,0 +1,236 @@
6.4 +/*
6.5 + * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
6.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6.7 + *
6.8 + * This code is free software; you can redistribute it and/or modify it
6.9 + * under the terms of the GNU General Public License version 2 only, as
6.10 + * published by the Free Software Foundation. Oracle designates this
6.11 + * particular file as subject to the "Classpath" exception as provided
6.12 + * by Oracle in the LICENSE file that accompanied this code.
6.13 + *
6.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
6.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
6.16 + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
6.17 + * version 2 for more details (a copy is included in the LICENSE file that
6.18 + * accompanied this code).
6.19 + *
6.20 + * You should have received a copy of the GNU General Public License version
6.21 + * 2 along with this work; if not, write to the Free Software Foundation,
6.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
6.23 + *
6.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
6.25 + * or visit www.oracle.com if you need additional information or have any
6.26 + * questions.
6.27 + */
6.28 +
6.29 +package java.util.regex;
6.30 +
6.31 +import java.util.HashMap;
6.32 +import java.util.Locale;
6.33 +
6.34 +enum UnicodeProp {
6.35 +
6.36 + ALPHABETIC {
6.37 + public boolean is(int ch) {
6.38 + return Character.isAlphabetic(ch);
6.39 + }
6.40 + },
6.41 +
6.42 + LETTER {
6.43 + public boolean is(int ch) {
6.44 + return Character.isLetter(ch);
6.45 + }
6.46 + },
6.47 +
6.48 + IDEOGRAPHIC {
6.49 + public boolean is(int ch) {
6.50 + return Character.isIdeographic(ch);
6.51 + }
6.52 + },
6.53 +
6.54 + LOWERCASE {
6.55 + public boolean is(int ch) {
6.56 + return Character.isLowerCase(ch);
6.57 + }
6.58 + },
6.59 +
6.60 + UPPERCASE {
6.61 + public boolean is(int ch) {
6.62 + return Character.isUpperCase(ch);
6.63 + }
6.64 + },
6.65 +
6.66 + TITLECASE {
6.67 + public boolean is(int ch) {
6.68 + return Character.isTitleCase(ch);
6.69 + }
6.70 + },
6.71 +
6.72 + WHITE_SPACE {
6.73 + // \p{Whitespace}
6.74 + public boolean is(int ch) {
6.75 + return ((((1 << Character.SPACE_SEPARATOR) |
6.76 + (1 << Character.LINE_SEPARATOR) |
6.77 + (1 << Character.PARAGRAPH_SEPARATOR)) >> Character.getType(ch)) & 1)
6.78 + != 0 || (ch >= 0x9 && ch <= 0xd) || (ch == 0x85);
6.79 + }
6.80 + },
6.81 +
6.82 + CONTROL {
6.83 + // \p{gc=Control}
6.84 + public boolean is(int ch) {
6.85 + return Character.getType(ch) == Character.CONTROL;
6.86 + }
6.87 + },
6.88 +
6.89 + PUNCTUATION {
6.90 + // \p{gc=Punctuation}
6.91 + public boolean is(int ch) {
6.92 + return ((((1 << Character.CONNECTOR_PUNCTUATION) |
6.93 + (1 << Character.DASH_PUNCTUATION) |
6.94 + (1 << Character.START_PUNCTUATION) |
6.95 + (1 << Character.END_PUNCTUATION) |
6.96 + (1 << Character.OTHER_PUNCTUATION) |
6.97 + (1 << Character.INITIAL_QUOTE_PUNCTUATION) |
6.98 + (1 << Character.FINAL_QUOTE_PUNCTUATION)) >> Character.getType(ch)) & 1)
6.99 + != 0;
6.100 + }
6.101 + },
6.102 +
6.103 + HEX_DIGIT {
6.104 + // \p{gc=Decimal_Number}
6.105 + // \p{Hex_Digit} -> PropList.txt: Hex_Digit
6.106 + public boolean is(int ch) {
6.107 + return DIGIT.is(ch) ||
6.108 + (ch >= 0x0030 && ch <= 0x0039) ||
6.109 + (ch >= 0x0041 && ch <= 0x0046) ||
6.110 + (ch >= 0x0061 && ch <= 0x0066) ||
6.111 + (ch >= 0xFF10 && ch <= 0xFF19) ||
6.112 + (ch >= 0xFF21 && ch <= 0xFF26) ||
6.113 + (ch >= 0xFF41 && ch <= 0xFF46);
6.114 + }
6.115 + },
6.116 +
6.117 + ASSIGNED {
6.118 + public boolean is(int ch) {
6.119 + return Character.getType(ch) != Character.UNASSIGNED;
6.120 + }
6.121 + },
6.122 +
6.123 + NONCHARACTER_CODE_POINT {
6.124 + // PropList.txt:Noncharacter_Code_Point
6.125 + public boolean is(int ch) {
6.126 + return (ch & 0xfffe) == 0xfffe || (ch >= 0xfdd0 && ch <= 0xfdef);
6.127 + }
6.128 + },
6.129 +
6.130 + DIGIT {
6.131 + // \p{gc=Decimal_Number}
6.132 + public boolean is(int ch) {
6.133 + return Character.isDigit(ch);
6.134 + }
6.135 + },
6.136 +
6.137 + ALNUM {
6.138 + // \p{alpha}
6.139 + // \p{digit}
6.140 + public boolean is(int ch) {
6.141 + return ALPHABETIC.is(ch) || DIGIT.is(ch);
6.142 + }
6.143 + },
6.144 +
6.145 + BLANK {
6.146 + // \p{Whitespace} --
6.147 + // [\N{LF} \N{VT} \N{FF} \N{CR} \N{NEL} -> 0xa, 0xb, 0xc, 0xd, 0x85
6.148 + // \p{gc=Line_Separator}
6.149 + // \p{gc=Paragraph_Separator}]
6.150 + public boolean is(int ch) {
6.151 + return Character.getType(ch) == Character.SPACE_SEPARATOR ||
6.152 + ch == 0x9; // \N{HT}
6.153 + }
6.154 + },
6.155 +
6.156 + GRAPH {
6.157 + // [^
6.158 + // \p{space}
6.159 + // \p{gc=Control}
6.160 + // \p{gc=Surrogate}
6.161 + // \p{gc=Unassigned}]
6.162 + public boolean is(int ch) {
6.163 + return ((((1 << Character.SPACE_SEPARATOR) |
6.164 + (1 << Character.LINE_SEPARATOR) |
6.165 + (1 << Character.PARAGRAPH_SEPARATOR) |
6.166 + (1 << Character.CONTROL) |
6.167 + (1 << Character.SURROGATE) |
6.168 + (1 << Character.UNASSIGNED)) >> Character.getType(ch)) & 1)
6.169 + == 0;
6.170 + }
6.171 + },
6.172 +
6.173 + PRINT {
6.174 + // \p{graph}
6.175 + // \p{blank}
6.176 + // -- \p{cntrl}
6.177 + public boolean is(int ch) {
6.178 + return (GRAPH.is(ch) || BLANK.is(ch)) && !CONTROL.is(ch);
6.179 + }
6.180 + },
6.181 +
6.182 + WORD {
6.183 + // \p{alpha}
6.184 + // \p{gc=Mark}
6.185 + // \p{digit}
6.186 + // \p{gc=Connector_Punctuation}
6.187 +
6.188 + public boolean is(int ch) {
6.189 + return ALPHABETIC.is(ch) ||
6.190 + ((((1 << Character.NON_SPACING_MARK) |
6.191 + (1 << Character.ENCLOSING_MARK) |
6.192 + (1 << Character.COMBINING_SPACING_MARK) |
6.193 + (1 << Character.DECIMAL_DIGIT_NUMBER) |
6.194 + (1 << Character.CONNECTOR_PUNCTUATION)) >> Character.getType(ch)) & 1)
6.195 + != 0;
6.196 + }
6.197 + };
6.198 +
6.199 + private final static HashMap<String, String> posix = new HashMap<>();
6.200 + private final static HashMap<String, String> aliases = new HashMap<>();
6.201 + static {
6.202 + posix.put("ALPHA", "ALPHABETIC");
6.203 + posix.put("LOWER", "LOWERCASE");
6.204 + posix.put("UPPER", "UPPERCASE");
6.205 + posix.put("SPACE", "WHITE_SPACE");
6.206 + posix.put("PUNCT", "PUNCTUATION");
6.207 + posix.put("XDIGIT","HEX_DIGIT");
6.208 + posix.put("ALNUM", "ALNUM");
6.209 + posix.put("CNTRL", "CONTROL");
6.210 + posix.put("DIGIT", "DIGIT");
6.211 + posix.put("BLANK", "BLANK");
6.212 + posix.put("GRAPH", "GRAPH");
6.213 + posix.put("PRINT", "PRINT");
6.214 +
6.215 + aliases.put("WHITESPACE", "WHITE_SPACE");
6.216 + aliases.put("HEXDIGIT","HEX_DIGIT");
6.217 + aliases.put("NONCHARACTERCODEPOINT", "NONCHARACTER_CODE_POINT");
6.218 + }
6.219 +
6.220 + public static UnicodeProp forName(String propName) {
6.221 + propName = propName.toUpperCase(Locale.ENGLISH);
6.222 + String alias = aliases.get(propName);
6.223 + if (alias != null)
6.224 + propName = alias;
6.225 + try {
6.226 + return valueOf (propName);
6.227 + } catch (IllegalArgumentException x) {}
6.228 + return null;
6.229 + }
6.230 +
6.231 + public static UnicodeProp forPOSIXName(String propName) {
6.232 + propName = posix.get(propName.toUpperCase(Locale.ENGLISH));
6.233 + if (propName == null)
6.234 + return null;
6.235 + return valueOf (propName);
6.236 + }
6.237 +
6.238 + public abstract boolean is(int ch);
6.239 +}
7.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
7.2 +++ b/rt/emul/compact/src/main/java/java/util/regex/package.html Mon Oct 07 16:13:27 2013 +0200
7.3 @@ -0,0 +1,66 @@
7.4 +<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
7.5 +<html>
7.6 +<head>
7.7 +<!--
7.8 +Copyright (c) 2000, 2006, Oracle and/or its affiliates. All rights reserved.
7.9 +DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7.10 +
7.11 +This code is free software; you can redistribute it and/or modify it
7.12 +under the terms of the GNU General Public License version 2 only, as
7.13 +published by the Free Software Foundation. Oracle designates this
7.14 +particular file as subject to the "Classpath" exception as provided
7.15 +by Oracle in the LICENSE file that accompanied this code.
7.16 +
7.17 +This code is distributed in the hope that it will be useful, but WITHOUT
7.18 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
7.19 +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
7.20 +version 2 for more details (a copy is included in the LICENSE file that
7.21 +accompanied this code).
7.22 +
7.23 +You should have received a copy of the GNU General Public License version
7.24 +2 along with this work; if not, write to the Free Software Foundation,
7.25 +Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
7.26 +
7.27 +Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
7.28 +or visit www.oracle.com if you need additional information or have any
7.29 +questions.
7.30 +-->
7.31 +
7.32 +</head>
7.33 +<body bgcolor="white">
7.34 +
7.35 +Classes for matching character sequences against patterns specified by regular
7.36 +expressions.
7.37 +
7.38 +<p> An instance of the {@link java.util.regex.Pattern} class represents a
7.39 +regular expression that is specified in string form in a syntax similar to
7.40 +that used by Perl.
7.41 +
7.42 +<p> Instances of the {@link java.util.regex.Matcher} class are used to match
7.43 +character sequences against a given pattern. Input is provided to matchers via
7.44 +the {@link java.lang.CharSequence} interface in order to support matching
7.45 +against characters from a wide variety of input sources. </p>
7.46 +
7.47 +<p> Unless otherwise noted, passing a <tt>null</tt> argument to a method
7.48 +in any class or interface in this package will cause a
7.49 +{@link java.lang.NullPointerException NullPointerException} to be thrown.
7.50 +
7.51 +<h2>Related Documentation</h2>
7.52 +
7.53 +<p> An excellent tutorial and overview of regular expressions is <a
7.54 +href="http://www.oreilly.com/catalog/regex/"><i>Mastering Regular
7.55 +Expressions</i>, Jeffrey E. F. Friedl, O'Reilly and Associates, 1997.</a> </p>
7.56 +
7.57 +<!--
7.58 +For overviews, tutorials, examples, guides, and tool documentation, please see:
7.59 +<ul>
7.60 + <li><a href="">##### REFER TO NON-SPEC DOCUMENTATION HERE #####</a>
7.61 +</ul>
7.62 +-->
7.63 +
7.64 +@since 1.4
7.65 +@author Mike McCloskey
7.66 +@author Mark Reinhold
7.67 +
7.68 +</body>
7.69 +</html>