| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | /* |
| 9 | * Licensed to the Apache Software Foundation (ASF) under one or more |
| 10 | * contributor license agreements. See the NOTICE file distributed with |
| 11 | * this work for additional information regarding copyright ownership. |
| 12 | * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 13 | * (the "License"); you may not use this file except in compliance with |
| 14 | * the License. You may obtain a copy of the License at |
| 15 | * |
| 16 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 17 | * |
| 18 | * Unless required by applicable law or agreed to in writing, software |
| 19 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 20 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 21 | * See the License for the specific language governing permissions and |
| 22 | * limitations under the License. |
| 23 | */ |
| 24 | |
| 25 | /* |
| 26 | * Originally part of Apache's Jakarta project (downloaded January 2012), |
| 27 | * this file has been extensively modified for integration into Saxon by |
| 28 | * Michael Kay, Saxonica. |
| 29 | */ |
| 30 | |
| 31 | package net.sf.saxon.regex; |
| 32 | |
| 33 | |
| 34 | import net.sf.saxon.tree.util.FastStringBuffer; |
| 35 | import net.sf.saxon.z.IntIterator; |
| 36 | |
| 37 | import java.util.function.IntPredicate; |
| 38 | |
| 39 | import java.util.ArrayList; |
| 40 | import java.util.Arrays; |
| 41 | import java.util.List; |
| 42 | |
| 43 | |
| 44 | /** |
| 45 | * RE is an efficient, lightweight regular expression evaluator/matcher |
| 46 | * class. Regular expressions are pattern descriptions which enable |
| 47 | * sophisticated matching of strings. In addition to being able to |
| 48 | * match a string against a pattern, you can also extract parts of the |
| 49 | * match. This is especially useful in text parsing! Details on the |
| 50 | * syntax of regular expression patterns are given below. |
| 51 | * <p>To compile a regular expression (RE), you can simply construct an RE |
| 52 | * matcher object from the string specification of the pattern, like this:</p> |
| 53 | * <pre> |
| 54 | * RE r = new RE("a*b"); |
| 55 | * </pre> |
| 56 | * <p>Once you have done this, you can call either of the RE.match methods to |
| 57 | * perform matching on a String. For example:</p> |
| 58 | * <pre> |
| 59 | * boolean matched = r.match("aaaab"); |
| 60 | * </pre> |
| 61 | * <p>will cause the boolean matched to be set to true because the |
| 62 | * pattern "a*b" matches the string "aaaab".</p> |
| 63 | * <p>If you were interested in the <i>number</i> of a's which matched the |
| 64 | * first part of our example expression, you could change the expression to |
| 65 | * "(a*)b". Then when you compiled the expression and matched it against |
| 66 | * something like "xaaaab", you would get results like this:</p> |
| 67 | * <pre> |
| 68 | * RE r = new RE("(a*)b"); // Compile expression |
| 69 | * boolean matched = r.match("xaaaab"); // Match against "xaaaab" |
| 70 | * |
| 71 | * String wholeExpr = r.getParen(0); // wholeExpr will be 'aaaab' |
| 72 | * String insideParens = r.getParen(1); // insideParens will be 'aaaa' |
| 73 | * |
| 74 | * int startWholeExpr = r.getParenStart(0); // startWholeExpr will be index 1 |
| 75 | * int endWholeExpr = r.getParenEnd(0); // endWholeExpr will be index 6 |
| 76 | * int lenWholeExpr = r.getParenLength(0); // lenWholeExpr will be 5 |
| 77 | * |
| 78 | * int startInside = r.getParenStart(1); // startInside will be index 1 |
| 79 | * int endInside = r.getParenEnd(1); // endInside will be index 5 |
| 80 | * int lenInside = r.getParenLength(1); // lenInside will be 4 |
| 81 | * </pre> |
| 82 | * <p>You can also refer to the contents of a parenthesized expression |
| 83 | * within a regular expression itself. This is called a |
| 84 | * 'backreference'. The first backreference in a regular expression is |
| 85 | * denoted by \1, the second by \2 and so on. So the expression:</p> |
| 86 | * <pre> |
| 87 | * ([0-9]+)=\1 |
| 88 | * </pre> |
| 89 | * <p>will match any string of the form n=n (like 0=0 or 2=2).</p> |
| 90 | * <p>The full regular expression syntax accepted by RE is as defined in the XSD 1.1 |
| 91 | * specification, modified by the XPath 2.0 or 3.0 specifications.</p> |
| 92 | * <p><b>Line terminators</b></p> |
| 93 | * <p>A line terminator is a one- or two-character sequence that marks |
| 94 | * the end of a line of the input character sequence. The following |
| 95 | * are recognized as line terminators:</p> |
| 96 | * <ul> |
| 97 | * <li>A newline (line feed) character ('\n'),</li> |
| 98 | * <li>A carriage-return character followed immediately by a newline character ("\r\n"),</li> |
| 99 | * <li>A standalone carriage-return character ('\r'),</li> |
| 100 | * <li>A next-line character ('\u0085'),</li> |
| 101 | * <li>A line-separator character ('\u2028'), or</li> |
| 102 | * <li>A paragraph-separator character ('\u2029).</li> |
| 103 | * </ul> |
| 104 | * <p>RE runs programs compiled by the RECompiler class. But the RE |
| 105 | * matcher class does not include the actual regular expression compiler |
| 106 | * for reasons of efficiency. In fact, if you want to pre-compile one |
| 107 | * or more regular expressions, the 'recompile' class can be invoked |
| 108 | * from the command line to produce compiled output like this:</p> |
| 109 | * <pre> |
| 110 | * // Pre-compiled regular expression "a*b" |
| 111 | * char[] re1Instructions = |
| 112 | * { |
| 113 | * 0x007c, 0x0000, 0x001a, 0x007c, 0x0000, 0x000d, 0x0041, |
| 114 | * 0x0001, 0x0004, 0x0061, 0x007c, 0x0000, 0x0003, 0x0047, |
| 115 | * 0x0000, 0xfff6, 0x007c, 0x0000, 0x0003, 0x004e, 0x0000, |
| 116 | * 0x0003, 0x0041, 0x0001, 0x0004, 0x0062, 0x0045, 0x0000, |
| 117 | * 0x0000, |
| 118 | * }; |
| 119 | * |
| 120 | * |
| 121 | * REProgram re1 = new REProgram(re1Instructions); |
| 122 | * </pre> |
| 123 | * <p>You can then construct a regular expression matcher (RE) object from |
| 124 | * the pre-compiled expression re1 and thus avoid the overhead of |
| 125 | * compiling the expression at runtime. If you require more dynamic |
| 126 | * regular expressions, you can construct a single RECompiler object and |
| 127 | * re-use it to compile each expression. Similarly, you can change the |
| 128 | * program run by a given matcher object at any time. However, RE and |
| 129 | * RECompiler are not threadsafe (for efficiency reasons, and because |
| 130 | * requiring thread safety in this class is deemed to be a rare |
| 131 | * requirement), so you will need to construct a separate compiler or |
| 132 | * matcher object for each thread (unless you do thread synchronization |
| 133 | * yourself). Once expression compiled into the REProgram object, REProgram |
| 134 | * can be safely shared across multiple threads and RE objects.</p> |
| 135 | * <p><i>ISSUES:</i></p> |
| 136 | * <ul> |
| 137 | * <li>Not *all* possibilities are considered for greediness when backreferences |
| 138 | * are involved (as POSIX suggests should be the case). The POSIX RE |
| 139 | * "(ac*)c*d[ac]*\1", when matched against "acdacaa" should yield a match |
| 140 | * of acdacaa where \1 is "a". This is not the case in this RE package, |
| 141 | * and actually Perl doesn't go to this extent either! Until someone |
| 142 | * actually complains about this, I'm not sure it's worth "fixing". |
| 143 | * If it ever is fixed, test #137 in RETest.txt should be updated.</li> |
| 144 | * </ul> |
| 145 | * <p>This library is based on the Apache Jakarta regex library as downloaded |
| 146 | * on 3 January 2012. Changes have been made to make the grammar and semantics conform to XSD |
| 147 | * and XPath rules; these changes are listed in source code comments in the |
| 148 | * RECompiler source code module.</p> |
| 149 | * |
| 150 | * @author <a href="mailto:[email protected]">Jonathan Locke</a> |
| 151 | * @author <a href="mailto:[email protected]">Tobias Schäfer</a> |
| 152 | * @author <a href="mailto:[email protected]">Michael Kay</a> |
| 153 | * @see RECompiler |
| 154 | */ |
| 155 | public class REMatcher { |
| 156 | |
| 157 | // Limits |
| 158 | static final int MAX_PAREN = 16; // Number of paren pairs |
| 159 | |
| 160 | // State of current program |
| 161 | REProgram program; // Compiled regular expression 'program' |
| 162 | UnicodeString search; // The string being matched against |
| 163 | History history = new History(); |
| 164 | int maxParen = MAX_PAREN; |
| 165 | |
| 166 | // Parenthesized subexpressions |
| 167 | State captureState = new State(); |
| 168 | |
| 169 | // Backreferences |
| 170 | int[] startBackref; // Lazily-allocated array of backref starts |
| 171 | int[] endBackref; // Lazily-allocated array of backref ends |
| 172 | |
| 173 | Operation operation; |
| 174 | boolean anchoredMatch; |
| 175 | |
| 176 | |
| 177 | /** |
| 178 | * Construct a matcher for a pre-compiled regular expression from program |
| 179 | * (bytecode) data. |
| 180 | * |
| 181 | * @param program Compiled regular expression program |
| 182 | * @see RECompiler |
| 183 | */ |
| 184 | public REMatcher(REProgram program) { |
| 185 | setProgram(program); |
| 186 | } |
| 187 | |
| 188 | /** |
| 189 | * Sets the current regular expression program used by this matcher object. |
| 190 | * |
| 191 | * @param program Regular expression program compiled by RECompiler. |
| 192 | * @see RECompiler |
| 193 | * @see REProgram |
| 194 | */ |
| 195 | public void setProgram(REProgram program) { |
| 196 | this.program = program; |
| 197 | if (program != null && program.maxParens != -1) { |
| 198 | this.operation = program.operation; |
| 199 | this.maxParen = program.maxParens; |
| 200 | } else { |
| 201 | this.maxParen = MAX_PAREN; |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | /** |
| 206 | * Returns the current regular expression program in use by this matcher object. |
| 207 | * |
| 208 | * @return Regular expression program |
| 209 | * @see #setProgram |
| 210 | */ |
| 211 | public REProgram getProgram() { |
| 212 | return program; |
| 213 | } |
| 214 | |
| 215 | /** |
| 216 | * Returns the number of parenthesized subexpressions available after a successful match. |
| 217 | * |
| 218 | * @return Number of available parenthesized subexpressions |
| 219 | */ |
| 220 | public int getParenCount() { |
| 221 | return captureState.parenCount; |
| 222 | } |
| 223 | |
| 224 | /** |
| 225 | * Gets the contents of a parenthesized subexpression after a successful match. |
| 226 | * |
| 227 | * @param which Nesting level of subexpression |
| 228 | * @return String |
| 229 | */ |
| 230 | public UnicodeString getParen(int which) { |
| 231 | int start; |
| 232 | if (which < captureState.parenCount && (start = getParenStart(which)) >= 0) { |
| 233 | return search.uSubstring(start, getParenEnd(which)); |
| 234 | } |
| 235 | return null; |
| 236 | } |
| 237 | |
| 238 | /** |
| 239 | * Returns the start index of a given paren level. |
| 240 | * |
| 241 | * @param which Nesting level of subexpression |
| 242 | * @return String index |
| 243 | */ |
| 244 | public final int getParenStart(int which) { |
| 245 | if (which < captureState.startn.length) { |
| 246 | return captureState.startn[which]; |
| 247 | } |
| 248 | return -1; |
| 249 | } |
| 250 | |
| 251 | /** |
| 252 | * Returns the end index of a given paren level. |
| 253 | * |
| 254 | * @param which Nesting level of subexpression |
| 255 | * @return String index |
| 256 | */ |
| 257 | public final int getParenEnd(int which) { |
| 258 | if (which < captureState.endn.length) { |
| 259 | return captureState.endn[which]; |
| 260 | } |
| 261 | return -1; |
| 262 | } |
| 263 | |
| 264 | /** |
| 265 | * Sets the start of a paren level |
| 266 | * |
| 267 | * @param which Which paren level |
| 268 | * @param i Index in input array |
| 269 | */ |
| 270 | protected final void setParenStart(int which, int i) { |
| 271 | while (which > captureState.startn.length - 1) { |
| 272 | int[] s2 = new int[captureState.startn.length * 2]; |
| 273 | System.arraycopy(captureState.startn, 0, s2, 0, captureState.startn.length); |
| 274 | Arrays.fill(s2, captureState.startn.length, s2.length, -1); |
| 275 | captureState.startn = s2; |
| 276 | } |
| 277 | captureState.startn[which] = i; |
| 278 | } |
| 279 | |
| 280 | /** |
| 281 | * Sets the end of a paren level |
| 282 | * |
| 283 | * @param which Which paren level |
| 284 | * @param i Index in input array |
| 285 | */ |
| 286 | protected final void setParenEnd(int which, int i) { |
| 287 | while (which > captureState.endn.length - 1) { |
| 288 | int[] e2 = new int[captureState.endn.length * 2]; |
| 289 | System.arraycopy(captureState.endn, 0, e2, 0, captureState.endn.length); |
| 290 | Arrays.fill(e2, captureState.endn.length, e2.length, -1); |
| 291 | captureState.endn = e2; |
| 292 | } |
| 293 | captureState.endn[which] = i; |
| 294 | } |
| 295 | |
| 296 | /** |
| 297 | * Clear any captured groups whose start position is at or beyond some specified position |
| 298 | * @param pos the specified position |
| 299 | */ |
| 300 | |
| 301 | protected void clearCapturedGroupsBeyond(int pos) { |
| 302 | for (int i = 0; i < captureState.startn.length; i++) { |
| 303 | if (captureState.startn[i] >= pos) { |
| 304 | captureState.endn[i] = captureState.startn[i]; |
| 305 | } |
| 306 | } |
| 307 | if (startBackref != null) { |
| 308 | for (int i = 0; i < startBackref.length; i++) { |
| 309 | if (startBackref[i] >= pos) { |
| 310 | endBackref[i] = startBackref[i]; |
| 311 | } |
| 312 | } |
| 313 | } |
| 314 | } |
| 315 | |
| 316 | /** |
| 317 | * Match the current regular expression program against the current |
| 318 | * input string, starting at index i of the input string. This method |
| 319 | * is only meant for internal use. |
| 320 | * |
| 321 | * @param i The input string index to start matching at |
| 322 | * @param anchored true if the regex must match all characters up to the end of the string |
| 323 | * @return True if the input matched the expression |
| 324 | */ |
| 325 | protected boolean matchAt(int i, boolean anchored) { |
| 326 | // Initialize start pointer, paren cache and paren count |
| 327 | captureState.parenCount = 1; |
| 328 | anchoredMatch = anchored; |
| 329 | setParenStart(0, i); |
| 330 | |
| 331 | // Allocate backref arrays (unless optimizations indicate otherwise) |
| 332 | if ((program.optimizationFlags & REProgram.OPT_HASBACKREFS) != 0) { |
| 333 | startBackref = new int[maxParen]; |
| 334 | endBackref = new int[maxParen]; |
| 335 | } |
| 336 | |
| 337 | // Match against string |
| 338 | int idx; |
| 339 | IntIterator iter = operation.iterateMatches(this, i); |
| 340 | if (iter.hasNext()) { |
| 341 | idx = iter.next(); |
| 342 | setParenEnd(0, idx); |
| 343 | return true; |
| 344 | } |
| 345 | |
| 346 | // Didn't match |
| 347 | captureState.parenCount = 0; |
| 348 | return false; |
| 349 | } |
| 350 | |
| 351 | /** |
| 352 | * Tests whether the regex matches a string in its entirety, anchored |
| 353 | * at both ends |
| 354 | * |
| 355 | * @param search the string to be matched |
| 356 | * @return true if the regex matches the whols string |
| 357 | */ |
| 358 | |
| 359 | public boolean anchoredMatch(UnicodeString search) { |
| 360 | this.search = search; |
| 361 | return matchAt(0, true); |
| 362 | } |
| 363 | |
| 364 | /** |
| 365 | * Matches the current regular expression program against a character array, |
| 366 | * starting at a given index. |
| 367 | * |
| 368 | * @param search String to match against |
| 369 | * @param i Index to start searching at |
| 370 | * @return True if string matched |
| 371 | */ |
| 372 | public boolean match(UnicodeString search, int i) { |
| 373 | //System.err.println("Matching '" + search + "'"); |
| 374 | |
| 375 | // Save string to search |
| 376 | this.search = search; |
| 377 | |
| 378 | // Clear the captured group state |
| 379 | captureState = new State(); |
| 380 | |
| 381 | // Can we optimize the search by looking for new lines? |
| 382 | if ((program.optimizationFlags & REProgram.OPT_HASBOL) == REProgram.OPT_HASBOL) { |
| 383 | // Non multi-line matching with BOL: Must match at '0' index |
| 384 | if (!program.flags.isMultiLine()) { |
| 385 | return i == 0 && checkPreconditions(i) && matchAt(i, false); |
| 386 | } |
| 387 | |
| 388 | // Multi-line matching with BOL: Seek to next line |
| 389 | int nl = i; |
| 390 | if (matchAt(nl, false)) { |
| 391 | return true; |
| 392 | } |
| 393 | while (true) { |
| 394 | nl = search.uIndexOf('\n', nl) + 1; |
| 395 | if (nl >= search.uLength() || nl <= 0) { |
| 396 | return false; // "^" does not match a NL at the end of the string |
| 397 | } else { |
| 398 | if (matchAt(nl, false)) { |
| 399 | return true; |
| 400 | } |
| 401 | } |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | // Is the string long enough to match? |
| 406 | int actualLength = search.uLength() - i; |
| 407 | if (actualLength < program.minimumLength) { |
| 408 | return false; |
| 409 | } |
| 410 | |
| 411 | // Can we optimize the search by looking for a prefix string? |
| 412 | if (program.prefix == null) { |
| 413 | if (program.initialCharClass != null) { |
| 414 | // no prefix known; but the first character must match a predicate |
| 415 | IntPredicate pred = program.initialCharClass; |
| 416 | for (; !search.isEnd(i); i++) { |
| 417 | if (pred.test(search.uCharAt(i))) { |
| 418 | if (matchAt(i, false)) { |
| 419 | return true; |
| 420 | } |
| 421 | } |
| 422 | } |
| 423 | return false; |
| 424 | } |
| 425 | // Check the preconditions |
| 426 | if (!checkPreconditions(i)) { |
| 427 | return false; |
| 428 | } |
| 429 | // Unprefixed matching must try for a match at each character |
| 430 | for (; !search.isEnd(i - 1); i++) { |
| 431 | // Try a match at index i |
| 432 | if (matchAt(i, false)) { |
| 433 | return true; |
| 434 | } |
| 435 | } |
| 436 | return false; |
| 437 | } else { |
| 438 | // Prefix-anchored matching is possible |
| 439 | UnicodeString prefix = program.prefix; |
| 440 | int prefixLength = prefix.uLength(); |
| 441 | boolean ignoreCase = program.flags.isCaseIndependent(); |
| 442 | for (; !search.isEnd(i + prefixLength - 1); i++) { |
| 443 | boolean prefixOK = true; |
| 444 | if (ignoreCase) { |
| 445 | for (int j = i, k = 0; k < prefixLength; j++, k++) { |
| 446 | if (!equalCaseBlind(search.uCharAt(j), prefix.uCharAt(k))) { |
| 447 | prefixOK = false; |
| 448 | break; |
| 449 | } |
| 450 | } |
| 451 | } else { |
| 452 | for (int j = i, k=0; k < prefixLength; j++, k++) { |
| 453 | if (search.uCharAt(j) != prefix.uCharAt(k)) { |
| 454 | prefixOK = false; |
| 455 | break; |
| 456 | } |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | // See if the whole prefix string matched |
| 461 | if (prefixOK) { |
| 462 | // We matched the full prefix at firstChar, so try it |
| 463 | if (matchAt(i, false)) { |
| 464 | return true; |
| 465 | } |
| 466 | } |
| 467 | } |
| 468 | return false; |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | /** |
| 473 | * Check the preconditions for a match, testing the precondition at every position |
| 474 | * from some start point |
| 475 | * @param start the start position for matching preconditions |
| 476 | * |
| 477 | */ |
| 478 | |
| 479 | private boolean checkPreconditions(int start) { |
| 480 | for (RegexPrecondition condition : program.preconditions) { |
| 481 | if (condition.fixedPosition != -1) { |
| 482 | boolean match = condition.operation.iterateMatches(this, condition.fixedPosition).hasNext(); |
| 483 | if (!match) { |
| 484 | return false; |
| 485 | } |
| 486 | } else { |
| 487 | int i = start; |
| 488 | if (i < condition.minPosition) { |
| 489 | i = condition.minPosition; |
| 490 | } |
| 491 | boolean found = false; |
| 492 | for (; !search.isEnd(i); i++) { |
| 493 | if ((condition.fixedPosition == -1 || condition.fixedPosition == i) && |
| 494 | condition.operation.iterateMatches(this, i).hasNext()) { |
| 495 | found = true; |
| 496 | break; |
| 497 | } |
| 498 | } |
| 499 | if (!found) { |
| 500 | return false; |
| 501 | } |
| 502 | } |
| 503 | } |
| 504 | return true; |
| 505 | } |
| 506 | |
| 507 | /** |
| 508 | * Matches the current regular expression program against a String. |
| 509 | * |
| 510 | * @param search String to match against |
| 511 | * @return True if string matched |
| 512 | */ |
| 513 | public boolean match(String search) { |
| 514 | UnicodeString uString = UnicodeString.makeUnicodeString(search); |
| 515 | return match(uString, 0); |
| 516 | } |
| 517 | |
| 518 | /** |
| 519 | * Splits a string into an array of strings on regular expression boundaries. |
| 520 | * This function works the same way as the Perl function of the same name. |
| 521 | * Given a regular expression of "[ab]+" and a string to split of |
| 522 | * "xyzzyababbayyzabbbab123", the result would be the array of Strings |
| 523 | * "[xyzzy, yyz, 123]". |
| 524 | * <p>Please note that the first string in the resulting array may be an empty |
| 525 | * string. This happens when the very first character of input string is |
| 526 | * matched by the pattern.</p> |
| 527 | * |
| 528 | * @param s String to split on this regular exression |
| 529 | * @return Array of strings |
| 530 | */ |
| 531 | public List<UnicodeString> split(UnicodeString s) { |
| 532 | // Create new vector |
| 533 | List<UnicodeString> v = new ArrayList<UnicodeString>(); |
| 534 | |
| 535 | // Start at position 0 and search the whole string |
| 536 | int pos = 0; |
| 537 | int len = s.uLength(); |
| 538 | |
| 539 | // Try a match at each position |
| 540 | while (pos < len && match(s, pos)) { |
| 541 | // Get start of match |
| 542 | int start = getParenStart(0); |
| 543 | |
| 544 | // Get end of match |
| 545 | int newpos = getParenEnd(0); |
| 546 | |
| 547 | // Check if no progress was made |
| 548 | if (newpos == pos) { |
| 549 | v.add(s.uSubstring(pos, start + 1)); |
| 550 | newpos++; |
| 551 | } else { |
| 552 | v.add(s.uSubstring(pos, start)); |
| 553 | } |
| 554 | |
| 555 | // Move to new position |
| 556 | pos = newpos; |
| 557 | } |
| 558 | |
| 559 | // Push remainder even if it's empty |
| 560 | UnicodeString remainder = s.uSubstring(pos, len); |
| 561 | v.add(remainder); |
| 562 | |
| 563 | // Return the list |
| 564 | return v; |
| 565 | } |
| 566 | |
| 567 | /** |
| 568 | * Substitutes a string for this regular expression in another string. |
| 569 | * This method works like the Perl function of the same name. |
| 570 | * Given a regular expression of "a*b", a String to substituteIn of |
| 571 | * "aaaabfooaaabgarplyaaabwackyb" and the substitution String "-", the |
| 572 | * resulting String returned by subst would be "-foo-garply-wacky-". |
| 573 | * <p>It is also possible to reference the contents of a parenthesized expression |
| 574 | * with $0, $1, ... $9. A regular expression of "http://[\\.\\w\\-\\?/~_@&=%]+", |
| 575 | * a String to substituteIn of "visit us: http://www.apache.org!" and the |
| 576 | * substitution String "<a href=\"$0\">$0</a>", the resulting String |
| 577 | * returned by subst would be |
| 578 | * "visit us: <a href=\"http://www.apache.org\">http://www.apache.org</a>!".</p> |
| 579 | * <p><i>Note:</i> $0 represents the whole match.</p> |
| 580 | * |
| 581 | * @param in String to substitute within |
| 582 | * @param replacement String to substitute for matches of this regular expression |
| 583 | * @return The string substituteIn with zero or more occurrences of the current |
| 584 | * regular expression replaced with the substitution String (if this regular |
| 585 | * expression object doesn't match at any position, the original String is returned |
| 586 | * unchanged). |
| 587 | */ |
| 588 | public CharSequence replace(UnicodeString in, UnicodeString replacement) { |
| 589 | // String to return |
| 590 | FastStringBuffer sb = new FastStringBuffer(in.uLength() * 2); |
| 591 | |
| 592 | // Start at position 0 and search the whole string |
| 593 | int pos = 0; |
| 594 | int len = in.uLength(); |
| 595 | |
| 596 | // Try a match at each position |
| 597 | while (pos < len && match(in, pos)) { |
| 598 | // Append chars from input string before match |
| 599 | for (int i = pos; i < getParenStart(0); i++) { |
| 600 | sb.appendWideChar(in.uCharAt(i)); |
| 601 | } |
| 602 | |
| 603 | if (!program.flags.isLiteral()) { |
| 604 | // Process references to captured substrings |
| 605 | int maxCapture = program.maxParens - 1; |
| 606 | |
| 607 | for (int i = 0; i < replacement.uLength(); i++) { |
| 608 | int ch = replacement.uCharAt(i); |
| 609 | if (ch == '\\') { |
| 610 | ch = replacement.uCharAt(++i); |
| 611 | if (ch == '\\' || ch == '$') { |
| 612 | sb.append((char) ch); |
| 613 | } else { |
| 614 | throw new RESyntaxException("Invalid escape '" + ch + "' in replacement string"); |
| 615 | } |
| 616 | } else if (ch == '$') { |
| 617 | ch = replacement.uCharAt(++i); |
| 618 | if (!(ch >= '0' && ch <= '9')) { |
| 619 | throw new RESyntaxException("$ in replacement string must be followed by a digit"); |
| 620 | } |
| 621 | int n = ch - '0'; |
| 622 | if (maxCapture <= 9) { |
| 623 | if (maxCapture >= n) { |
| 624 | UnicodeString captured = getParen(n); |
| 625 | if (captured != null) { |
| 626 | for (int j = 0; j < captured.uLength(); j++) { |
| 627 | sb.appendWideChar(captured.uCharAt(j)); |
| 628 | } |
| 629 | } |
| 630 | } else { |
| 631 | // append a zero-length string (no-op) |
| 632 | } |
| 633 | } else { |
| 634 | while (true) { |
| 635 | if (++i >= replacement.uLength()) { |
| 636 | break; |
| 637 | } |
| 638 | ch = replacement.uCharAt(i); |
| 639 | if (ch >= '0' && ch <= '9') { |
| 640 | int m = n * 10 + (ch - '0'); |
| 641 | if (m > maxCapture) { |
| 642 | i--; |
| 643 | break; |
| 644 | } else { |
| 645 | n = m; |
| 646 | } |
| 647 | } else { |
| 648 | i--; |
| 649 | break; |
| 650 | } |
| 651 | } |
| 652 | UnicodeString captured = getParen(n); |
| 653 | if (captured != null) { |
| 654 | for (int j = 0; j < captured.uLength(); j++) { |
| 655 | sb.appendWideChar(captured.uCharAt(j)); |
| 656 | } |
| 657 | } |
| 658 | } |
| 659 | } else { |
| 660 | sb.appendWideChar(ch); |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | } else { |
| 665 | // Append substitution without processing backreferences |
| 666 | for (int i = 0; i < replacement.uLength(); i++) { |
| 667 | sb.appendWideChar(replacement.uCharAt(i)); |
| 668 | } |
| 669 | } |
| 670 | |
| 671 | // Move forward, skipping past match |
| 672 | int newpos = getParenEnd(0); |
| 673 | |
| 674 | // We always want to make progress! |
| 675 | if (newpos == pos) { |
| 676 | newpos++; |
| 677 | } |
| 678 | |
| 679 | // Try new position |
| 680 | pos = newpos; |
| 681 | |
| 682 | } |
| 683 | |
| 684 | // If there's remaining input, append it |
| 685 | for (int i = pos; i < len; i++) { |
| 686 | sb.appendWideChar(in.uCharAt(i)); |
| 687 | } |
| 688 | |
| 689 | // Return string buffer |
| 690 | return sb.condense(); |
| 691 | } |
| 692 | |
| 693 | |
| 694 | /** |
| 695 | * Test whether the character at a given position is a newline |
| 696 | * |
| 697 | * @param i the position of the character to be tested |
| 698 | * @return true if character at i-th position in the <code>search</code> string is a newline |
| 699 | */ |
| 700 | boolean isNewline(int i) { |
| 701 | return search.uCharAt(i) == '\n'; |
| 702 | } |
| 703 | |
| 704 | /** |
| 705 | * Compares two characters ignoring case. |
| 706 | * |
| 707 | * @param c1 first character to compare. |
| 708 | * @param c2 second character to compare. |
| 709 | * @return true the first character is equal to the second ignoring case. |
| 710 | */ |
| 711 | boolean equalCaseBlind(int c1, int c2) { |
| 712 | if (c1 == c2) { |
| 713 | return true; |
| 714 | } |
| 715 | for (int v : CaseVariants.getCaseVariants(c2)) { |
| 716 | if (c1 == v) { |
| 717 | return true; |
| 718 | } |
| 719 | } |
| 720 | return false; |
| 721 | } |
| 722 | |
| 723 | public State captureState() { |
| 724 | return new State(captureState); |
| 725 | } |
| 726 | |
| 727 | public void resetState(State state) { |
| 728 | captureState = new State(state); |
| 729 | } |
| 730 | |
| 731 | public static class State { |
| 732 | int parenCount; // Number of subexpressions matched (num open parens + 1) |
| 733 | int[] startn; // Lazily-allocated array of sub-expression starts |
| 734 | int[] endn; // Lazily-allocated array of sub-expression ends |
| 735 | |
| 736 | public State() { |
| 737 | parenCount = 0; |
| 738 | startn = new int[3]; |
| 739 | startn[0] = startn[1] = startn[2] = -1; |
| 740 | endn = new int[3]; |
| 741 | endn[0] = endn[1] = endn[2] = -1; |
| 742 | } |
| 743 | |
| 744 | public State(State s) { |
| 745 | parenCount = s.parenCount; |
| 746 | startn = Arrays.copyOf(s.startn, s.startn.length); |
| 747 | endn = Arrays.copyOf(s.endn, s.endn.length); |
| 748 | } |
| 749 | }; |
| 750 | } |