/interpreter/tags/at2dist130208/src/edu/vub/util/regexp/RE.java

http://ambienttalk.googlecode.com/ · Java · 1959 lines · 1127 code · 190 blank · 642 comment · 544 complexity · 21580fc622e8e962bff57ce154485c7c MD5 · raw file

Large files are truncated click here to view the full file

  1. /* gnu/regexp/RE.java
  2. Copyright (C) 2006 Free Software Foundation, Inc.
  3. This file is part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; see the file COPYING. If not, write to the
  14. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  15. 02110-1301 USA.
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package edu.vub.util.regexp;
  32. import java.io.InputStream;
  33. import java.io.Serializable;
  34. import java.util.Vector;
  35. /**
  36. * RE provides the user interface for compiling and matching regular
  37. * expressions.
  38. * <P>
  39. * A regular expression object (class RE) is compiled by constructing it
  40. * from a String, StringBuffer or character array, with optional
  41. * compilation flags (below)
  42. * and an optional syntax specification (see RESyntax; if not specified,
  43. * <code>RESyntax.RE_SYNTAX_PERL5</code> is used).
  44. * <P>
  45. * Once compiled, a regular expression object is reusable as well as
  46. * threadsafe: multiple threads can use the RE instance simultaneously
  47. * to match against different input text.
  48. * <P>
  49. * Various methods attempt to match input text against a compiled
  50. * regular expression. These methods are:
  51. * <LI><code>isMatch</code>: returns true if the input text in its
  52. * entirety matches the regular expression pattern.
  53. * <LI><code>getMatch</code>: returns the first match found in the
  54. * input text, or null if no match is found.
  55. * <LI><code>getAllMatches</code>: returns an array of all
  56. * non-overlapping matches found in the input text. If no matches are
  57. * found, the array is zero-length.
  58. * <LI><code>substitute</code>: substitute the first occurence of the
  59. * pattern in the input text with a replacement string (which may
  60. * include metacharacters $0-$9, see REMatch.substituteInto).
  61. * <LI><code>substituteAll</code>: same as above, but repeat for each
  62. * match before returning.
  63. * <LI><code>getMatchEnumeration</code>: returns an REMatchEnumeration
  64. * object that allows iteration over the matches (see
  65. * REMatchEnumeration for some reasons why you may want to do this
  66. * instead of using <code>getAllMatches</code>.
  67. * <P>
  68. *
  69. * These methods all have similar argument lists. The input can be a
  70. * String, a character array, a StringBuffer, or an
  71. * InputStream of some sort. Note that when using an
  72. * InputStream, the stream read position cannot be guaranteed after
  73. * attempting a match (this is not a bug, but a consequence of the way
  74. * regular expressions work). Using an REMatchEnumeration can
  75. * eliminate most positioning problems.
  76. *
  77. * <P>
  78. *
  79. * The optional index argument specifies the offset from the beginning
  80. * of the text at which the search should start (see the descriptions
  81. * of some of the execution flags for how this can affect positional
  82. * pattern operators). For an InputStream, this means an
  83. * offset from the current read position, so subsequent calls with the
  84. * same index argument on an InputStream will not
  85. * necessarily access the same position on the stream, whereas
  86. * repeated searches at a given index in a fixed string will return
  87. * consistent results.
  88. *
  89. * <P>
  90. * You can optionally affect the execution environment by using a
  91. * combination of execution flags (constants listed below).
  92. *
  93. * <P>
  94. * All operations on a regular expression are performed in a
  95. * thread-safe manner.
  96. *
  97. * @author <A HREF="mailto:wes@cacas.org">Wes Biggs</A>
  98. * @version 1.1.5-dev, to be released
  99. */
  100. public class RE extends REToken {
  101. private static final class IntPair implements Serializable {
  102. public int first, second;
  103. }
  104. private static final class CharUnit implements Serializable {
  105. public char ch;
  106. public boolean bk;
  107. }
  108. // This String will be returned by getVersion()
  109. private static final String VERSION = "1.1.5-dev";
  110. // These are, respectively, the first and last tokens in our linked list
  111. // If there is only one token, firstToken == lastToken
  112. private REToken firstToken, lastToken;
  113. // This is the number of subexpressions in this regular expression,
  114. // with a minimum value of zero. Returned by getNumSubs()
  115. private int numSubs;
  116. /** Minimum length, in characters, of any possible match. */
  117. private int minimumLength;
  118. private int maximumLength;
  119. /**
  120. * Compilation flag. Do not differentiate case. Subsequent
  121. * searches using this RE will be case insensitive.
  122. */
  123. public static final int REG_ICASE = 0x02;
  124. /**
  125. * Compilation flag. The match-any-character operator (dot)
  126. * will match a newline character. When set this overrides the syntax
  127. * bit RE_DOT_NEWLINE (see RESyntax for details). This is equivalent to
  128. * the "/s" operator in Perl.
  129. */
  130. public static final int REG_DOT_NEWLINE = 0x04;
  131. /**
  132. * Compilation flag. Use multiline mode. In this mode, the ^ and $
  133. * anchors will match based on newlines within the input. This is
  134. * equivalent to the "/m" operator in Perl.
  135. */
  136. public static final int REG_MULTILINE = 0x08;
  137. /**
  138. * Execution flag.
  139. * The match-beginning operator (^) will not match at the beginning
  140. * of the input string. Useful for matching on a substring when you
  141. * know the context of the input is such that position zero of the
  142. * input to the match test is not actually position zero of the text.
  143. * <P>
  144. * This example demonstrates the results of various ways of matching on
  145. * a substring.
  146. * <P>
  147. * <CODE>
  148. * String s = "food bar fool";<BR>
  149. * RE exp = new RE("^foo.");<BR>
  150. * REMatch m0 = exp.getMatch(s);<BR>
  151. * REMatch m1 = exp.getMatch(s.substring(8));<BR>
  152. * REMatch m2 = exp.getMatch(s.substring(8),0,RE.REG_NOTBOL); <BR>
  153. * REMatch m3 = exp.getMatch(s,8); <BR>
  154. * REMatch m4 = exp.getMatch(s,8,RE.REG_ANCHORINDEX); <BR>
  155. * <P>
  156. * // Results:<BR>
  157. * // m0.toString(): "food"<BR>
  158. * // m1.toString(): "fool"<BR>
  159. * // m2.toString(): null<BR>
  160. * // m3.toString(): null<BR>
  161. * // m4.toString(): "fool"<BR>
  162. * </CODE>
  163. */
  164. public static final int REG_NOTBOL = 0x10;
  165. /**
  166. * Execution flag.
  167. * The match-end operator ($) does not match at the end
  168. * of the input string. Useful for matching on substrings.
  169. */
  170. public static final int REG_NOTEOL = 0x20;
  171. /**
  172. * Execution flag.
  173. * When a match method is invoked that starts matching at a non-zero
  174. * index into the input, treat the input as if it begins at the index
  175. * given. The effect of this flag is that the engine does not "see"
  176. * any text in the input before the given index. This is useful so
  177. * that the match-beginning operator (^) matches not at position 0
  178. * in the input string, but at the position the search started at
  179. * (based on the index input given to the getMatch function). See
  180. * the example under REG_NOTBOL. It also affects the use of the \&lt;
  181. * and \b operators.
  182. */
  183. public static final int REG_ANCHORINDEX = 0x40;
  184. /**
  185. * Execution flag.
  186. * The substitute and substituteAll methods will not attempt to
  187. * interpolate occurrences of $1-$9 in the replacement text with
  188. * the corresponding subexpressions. For example, you may want to
  189. * replace all matches of "one dollar" with "$1".
  190. */
  191. public static final int REG_NO_INTERPOLATE = 0x80;
  192. /**
  193. * Execution flag.
  194. * Try to match the whole input string. An implicit match-end operator
  195. * is added to this regexp.
  196. */
  197. public static final int REG_TRY_ENTIRE_MATCH = 0x0100;
  198. /**
  199. * Execution flag.
  200. * The substitute and substituteAll methods will treat the
  201. * character '\' in the replacement as an escape to a literal
  202. * character. In this case "\n", "\$", "\\", "\x40" and "\012"
  203. * will become "n", "$", "\", "x40" and "012" respectively.
  204. * This flag has no effect if REG_NO_INTERPOLATE is set on.
  205. */
  206. public static final int REG_REPLACE_USE_BACKSLASHESCAPE = 0x0200;
  207. /** Returns a string representing the version of the edu.vub.util.regexp package. */
  208. public static final String version() {
  209. return VERSION;
  210. }
  211. /**
  212. * Constructs a regular expression pattern buffer without any compilation
  213. * flags set, and using the default syntax (RESyntax.RE_SYNTAX_PERL5).
  214. *
  215. * @param pattern A regular expression pattern, in the form of a String,
  216. * StringBuffer or char[]. Other input types will be converted to
  217. * strings using the toString() method.
  218. * @exception REException The input pattern could not be parsed.
  219. * @exception NullPointerException The pattern was null.
  220. */
  221. public RE(Object pattern) throws REException {
  222. this(pattern,0,RESyntax.RE_SYNTAX_PERL5,0,0);
  223. }
  224. /**
  225. * Constructs a regular expression pattern buffer using the specified
  226. * compilation flags and the default syntax (RESyntax.RE_SYNTAX_PERL5).
  227. *
  228. * @param pattern A regular expression pattern, in the form of a String,
  229. * StringBuffer, or char[]. Other input types will be converted to
  230. * strings using the toString() method.
  231. * @param cflags The logical OR of any combination of the compilation flags listed above.
  232. * @exception REException The input pattern could not be parsed.
  233. * @exception NullPointerException The pattern was null.
  234. */
  235. public RE(Object pattern, int cflags) throws REException {
  236. this(pattern,cflags,RESyntax.RE_SYNTAX_PERL5,0,0);
  237. }
  238. /**
  239. * Constructs a regular expression pattern buffer using the specified
  240. * compilation flags and regular expression syntax.
  241. *
  242. * @param pattern A regular expression pattern, in the form of a String,
  243. * StringBuffer, or char[]. Other input types will be converted to
  244. * strings using the toString() method.
  245. * @param cflags The logical OR of any combination of the compilation flags listed above.
  246. * @param syntax The type of regular expression syntax to use.
  247. * @exception REException The input pattern could not be parsed.
  248. * @exception NullPointerException The pattern was null.
  249. */
  250. public RE(Object pattern, int cflags, RESyntax syntax) throws REException {
  251. this(pattern,cflags,syntax,0,0);
  252. }
  253. // internal constructor used for alternation
  254. private RE(REToken first, REToken last,int subs, int subIndex, int minLength, int maxLength) {
  255. super(subIndex);
  256. firstToken = first;
  257. lastToken = last;
  258. numSubs = subs;
  259. minimumLength = minLength;
  260. maximumLength = maxLength;
  261. addToken(new RETokenEndSub(subIndex));
  262. }
  263. private RE(Object patternObj, int cflags, RESyntax syntax, int myIndex, int nextSub) throws REException {
  264. super(myIndex); // Subexpression index of this token.
  265. initialize(patternObj, cflags, syntax, myIndex, nextSub);
  266. }
  267. // For use by subclasses
  268. protected RE() { super(0); }
  269. // The meat of construction
  270. protected void initialize(Object patternObj, int cflags, RESyntax syntax, int myIndex, int nextSub) throws REException {
  271. char[] pattern;
  272. if (patternObj instanceof String) {
  273. pattern = ((String) patternObj).toCharArray();
  274. } else if (patternObj instanceof char[]) {
  275. pattern = (char[]) patternObj;
  276. } else if (patternObj instanceof StringBuffer) {
  277. pattern = new char [((StringBuffer) patternObj).length()];
  278. ((StringBuffer) patternObj).getChars(0,pattern.length,pattern,0);
  279. } else {
  280. pattern = patternObj.toString().toCharArray();
  281. }
  282. int pLength = pattern.length;
  283. numSubs = 0; // Number of subexpressions in this token.
  284. Vector branches = null;
  285. // linked list of tokens (sort of -- some closed loops can exist)
  286. firstToken = lastToken = null;
  287. // Precalculate these so we don't pay for the math every time we
  288. // need to access them.
  289. boolean insens = ((cflags & REG_ICASE) > 0);
  290. // Parse pattern into tokens. Does anyone know if it's more efficient
  291. // to use char[] than a String.charAt()? I'm assuming so.
  292. // index tracks the position in the char array
  293. int index = 0;
  294. // this will be the current parse character (pattern[index])
  295. CharUnit unit = new CharUnit();
  296. // This is used for {x,y} calculations
  297. IntPair minMax = new IntPair();
  298. // Buffer a token so we can create a TokenRepeated, etc.
  299. REToken currentToken = null;
  300. char ch;
  301. boolean quot = false;
  302. // Saved syntax and flags.
  303. RESyntax savedSyntax = null;
  304. int savedCflags = 0;
  305. boolean flagsSaved = false;
  306. while (index < pLength) {
  307. // read the next character unit (including backslash escapes)
  308. index = getCharUnit(pattern,index,unit,quot);
  309. if (unit.bk)
  310. if (unit.ch == 'Q') {
  311. quot = true;
  312. continue;
  313. } else if (unit.ch == 'E') {
  314. quot = false;
  315. continue;
  316. }
  317. if (quot)
  318. unit.bk = false;
  319. // ALTERNATION OPERATOR
  320. // \| or | (if RE_NO_BK_VBAR) or newline (if RE_NEWLINE_ALT)
  321. // not available if RE_LIMITED_OPS is set
  322. // TODO: the '\n' literal here should be a test against REToken.newline,
  323. // which unfortunately may be more than a single character.
  324. if ( ( (unit.ch == '|' && (syntax.get(RESyntax.RE_NO_BK_VBAR) ^ (unit.bk || quot)))
  325. || (syntax.get(RESyntax.RE_NEWLINE_ALT) && (unit.ch == '\n') && !(unit.bk || quot)) )
  326. && !syntax.get(RESyntax.RE_LIMITED_OPS)) {
  327. // make everything up to here be a branch. create vector if nec.
  328. addToken(currentToken);
  329. RE theBranch = new RE(firstToken, lastToken, numSubs, subIndex, minimumLength, maximumLength);
  330. minimumLength = 0;
  331. maximumLength = 0;
  332. if (branches == null) {
  333. branches = new Vector();
  334. }
  335. branches.addElement(theBranch);
  336. firstToken = lastToken = currentToken = null;
  337. }
  338. // INTERVAL OPERATOR:
  339. // {x} | {x,} | {x,y} (RE_INTERVALS && RE_NO_BK_BRACES)
  340. // \{x\} | \{x,\} | \{x,y\} (RE_INTERVALS && !RE_NO_BK_BRACES)
  341. //
  342. // OPEN QUESTION:
  343. // what is proper interpretation of '{' at start of string?
  344. //
  345. // This method used to check "repeat.empty.token" to avoid such regexp
  346. // as "(a*){2,}", but now "repeat.empty.token" is allowed.
  347. else if ((unit.ch == '{') && syntax.get(RESyntax.RE_INTERVALS) && (syntax.get(RESyntax.RE_NO_BK_BRACES) ^ (unit.bk || quot))) {
  348. int newIndex = getMinMax(pattern,index,minMax,syntax);
  349. if (newIndex > index) {
  350. if (minMax.first > minMax.second)
  351. throw new REException("an interval''s minimum is greater than its maximum",REException.REG_BADRPT,newIndex);
  352. if (currentToken == null)
  353. throw new REException("quantifier (?*+{}) without preceding token",REException.REG_BADRPT,newIndex);
  354. if (currentToken instanceof RETokenRepeated)
  355. throw new REException("attempted to repeat a token that is already repeated",REException.REG_BADRPT,newIndex);
  356. if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
  357. throw new REException("repeated token is zero-width assertion",REException.REG_BADRPT,newIndex);
  358. index = newIndex;
  359. currentToken = setRepeated(currentToken,minMax.first,minMax.second,index);
  360. }
  361. else {
  362. addToken(currentToken);
  363. currentToken = new RETokenChar(subIndex,unit.ch,insens);
  364. }
  365. }
  366. // LIST OPERATOR:
  367. // [...] | [^...]
  368. else if ((unit.ch == '[') && !(unit.bk || quot)) {
  369. // Create a new RETokenOneOf
  370. ParseCharClassResult result = parseCharClass(
  371. subIndex, pattern, index, pLength, cflags, syntax, 0);
  372. addToken(currentToken);
  373. currentToken = result.token;
  374. index = result.index;
  375. }
  376. // SUBEXPRESSIONS
  377. // (...) | \(...\) depending on RE_NO_BK_PARENS
  378. else if ((unit.ch == '(') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) {
  379. boolean pure = false;
  380. boolean comment = false;
  381. boolean lookAhead = false;
  382. boolean lookBehind = false;
  383. boolean independent = false;
  384. boolean negativelh = false;
  385. boolean negativelb = false;
  386. if ((index+1 < pLength) && (pattern[index] == '?')) {
  387. switch (pattern[index+1]) {
  388. case '!':
  389. if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
  390. pure = true;
  391. negativelh = true;
  392. lookAhead = true;
  393. index += 2;
  394. }
  395. break;
  396. case '=':
  397. if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
  398. pure = true;
  399. lookAhead = true;
  400. index += 2;
  401. }
  402. break;
  403. case '<':
  404. // We assume that if the syntax supports look-ahead,
  405. // it also supports look-behind.
  406. if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
  407. index++;
  408. switch (pattern[index +1]) {
  409. case '!':
  410. pure = true;
  411. negativelb = true;
  412. lookBehind = true;
  413. index += 2;
  414. break;
  415. case '=':
  416. pure = true;
  417. lookBehind = true;
  418. index += 2;
  419. }
  420. }
  421. break;
  422. case '>':
  423. // We assume that if the syntax supports look-ahead,
  424. // it also supports independent group.
  425. if (syntax.get(RESyntax.RE_LOOKAHEAD)) {
  426. pure = true;
  427. independent = true;
  428. index += 2;
  429. }
  430. break;
  431. case 'i':
  432. case 'd':
  433. case 'm':
  434. case 's':
  435. // case 'u': not supported
  436. // case 'x': not supported
  437. case '-':
  438. if (!syntax.get(RESyntax.RE_EMBEDDED_FLAGS)) break;
  439. // Set or reset syntax flags.
  440. int flagIndex = index + 1;
  441. int endFlag = -1;
  442. RESyntax newSyntax = new RESyntax(syntax);
  443. int newCflags = cflags;
  444. boolean negate = false;
  445. while (flagIndex < pLength && endFlag < 0) {
  446. switch(pattern[flagIndex]) {
  447. case 'i':
  448. if (negate)
  449. newCflags &= ~REG_ICASE;
  450. else
  451. newCflags |= REG_ICASE;
  452. flagIndex++;
  453. break;
  454. case 'd':
  455. if (negate)
  456. newSyntax.setLineSeparator(RESyntax.DEFAULT_LINE_SEPARATOR);
  457. else
  458. newSyntax.setLineSeparator("\n");
  459. flagIndex++;
  460. break;
  461. case 'm':
  462. if (negate)
  463. newCflags &= ~REG_MULTILINE;
  464. else
  465. newCflags |= REG_MULTILINE;
  466. flagIndex++;
  467. break;
  468. case 's':
  469. if (negate)
  470. newCflags &= ~REG_DOT_NEWLINE;
  471. else
  472. newCflags |= REG_DOT_NEWLINE;
  473. flagIndex++;
  474. break;
  475. // case 'u': not supported
  476. // case 'x': not supported
  477. case '-':
  478. negate = true;
  479. flagIndex++;
  480. break;
  481. case ':':
  482. case ')':
  483. endFlag = pattern[flagIndex];
  484. break;
  485. default:
  486. throw new REException("quantifier (?*+{}) without preceding token", REException.REG_BADRPT, index);
  487. }
  488. }
  489. if (endFlag == ')') {
  490. syntax = newSyntax;
  491. cflags = newCflags;
  492. insens = ((cflags & REG_ICASE) > 0);
  493. // This can be treated as though it were a comment.
  494. comment = true;
  495. index = flagIndex - 1;
  496. break;
  497. }
  498. if (endFlag == ':') {
  499. savedSyntax = syntax;
  500. savedCflags = cflags;
  501. flagsSaved = true;
  502. syntax = newSyntax;
  503. cflags = newCflags;
  504. insens = ((cflags & REG_ICASE) > 0);
  505. index = flagIndex -1;
  506. // Fall through to the next case.
  507. }
  508. else {
  509. throw new REException("unmatched parenthesis", REException.REG_ESUBREG,index);
  510. }
  511. case ':':
  512. if (syntax.get(RESyntax.RE_PURE_GROUPING)) {
  513. pure = true;
  514. index += 2;
  515. }
  516. break;
  517. case '#':
  518. if (syntax.get(RESyntax.RE_COMMENTS)) {
  519. comment = true;
  520. }
  521. break;
  522. default:
  523. throw new REException("quantifier (?*+{}) without preceding token", REException.REG_BADRPT, index);
  524. }
  525. }
  526. if (index >= pLength) {
  527. throw new REException("unmatched parenthesis", REException.REG_ESUBREG,index);
  528. }
  529. // find end of subexpression
  530. int endIndex = index;
  531. int nextIndex = index;
  532. int nested = 0;
  533. while ( ((nextIndex = getCharUnit(pattern,endIndex,unit,false)) > 0)
  534. && !(nested == 0 && (unit.ch == ')') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot))) ) {
  535. if ((endIndex = nextIndex) >= pLength)
  536. throw new REException("unexpected end of subexpression",REException.REG_ESUBREG,nextIndex);
  537. else if ((unit.ch == '[') && !(unit.bk || quot)) {
  538. // I hate to do something similar to the LIST OPERATOR matters
  539. // above, but ...
  540. int listIndex = nextIndex;
  541. if (listIndex < pLength && pattern[listIndex] == '^') listIndex++;
  542. if (listIndex < pLength && pattern[listIndex] == ']') listIndex++;
  543. int listEndIndex = -1;
  544. int listNest = 0;
  545. while (listIndex < pLength && listEndIndex < 0) {
  546. switch(pattern[listIndex++]) {
  547. case '\\':
  548. listIndex++;
  549. break;
  550. case '[':
  551. // Sun's API document says that regexp like "[a-d[m-p]]"
  552. // is legal. Even something like "[[[^]]]]" is accepted.
  553. listNest++;
  554. if (listIndex < pLength && pattern[listIndex] == '^') listIndex++;
  555. if (listIndex < pLength && pattern[listIndex] == ']') listIndex++;
  556. break;
  557. case ']':
  558. if (listNest == 0)
  559. listEndIndex = listIndex;
  560. listNest--;
  561. break;
  562. }
  563. }
  564. if (listEndIndex >= 0) {
  565. nextIndex = listEndIndex;
  566. if ((endIndex = nextIndex) >= pLength)
  567. throw new REException("unexpected end of subexpression",REException.REG_ESUBREG,nextIndex);
  568. else
  569. continue;
  570. }
  571. throw new REException("unexpected end of subexpression",REException.REG_ESUBREG,nextIndex);
  572. }
  573. else if (unit.ch == '(' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot)))
  574. nested++;
  575. else if (unit.ch == ')' && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot)))
  576. nested--;
  577. }
  578. // endIndex is now position at a ')','\)'
  579. // nextIndex is end of string or position after ')' or '\)'
  580. if (comment) index = nextIndex;
  581. else { // not a comment
  582. // create RE subexpression as token.
  583. addToken(currentToken);
  584. if (!pure) {
  585. numSubs++;
  586. }
  587. int useIndex = (pure || lookAhead || lookBehind || independent) ?
  588. 0 : nextSub + numSubs;
  589. currentToken = new RE(String.valueOf(pattern,index,endIndex-index).toCharArray(),cflags,syntax,useIndex,nextSub + numSubs);
  590. numSubs += ((RE) currentToken).getNumSubs();
  591. if (lookAhead) {
  592. currentToken = new RETokenLookAhead(currentToken,negativelh);
  593. }
  594. else if (lookBehind) {
  595. currentToken = new RETokenLookBehind(currentToken,negativelb);
  596. }
  597. else if (independent) {
  598. currentToken = new RETokenIndependent(currentToken);
  599. }
  600. index = nextIndex;
  601. if (flagsSaved) {
  602. syntax = savedSyntax;
  603. cflags = savedCflags;
  604. insens = ((cflags & REG_ICASE) > 0);
  605. flagsSaved = false;
  606. }
  607. } // not a comment
  608. } // subexpression
  609. // UNMATCHED RIGHT PAREN
  610. // ) or \) throw exception if
  611. // !syntax.get(RESyntax.RE_UNMATCHED_RIGHT_PAREN_ORD)
  612. else if (!syntax.get(RESyntax.RE_UNMATCHED_RIGHT_PAREN_ORD) && ((unit.ch == ')') && (syntax.get(RESyntax.RE_NO_BK_PARENS) ^ (unit.bk || quot)))) {
  613. throw new REException("unmatched parenthesis",REException.REG_EPAREN,index);
  614. }
  615. // START OF LINE OPERATOR
  616. // ^
  617. else if ((unit.ch == '^') && !(unit.bk || quot)) {
  618. addToken(currentToken);
  619. currentToken = null;
  620. addToken(new RETokenStart(subIndex,((cflags & REG_MULTILINE) > 0) ? syntax.getLineSeparator() : null));
  621. }
  622. // END OF LINE OPERATOR
  623. // $
  624. else if ((unit.ch == '$') && !(unit.bk || quot)) {
  625. addToken(currentToken);
  626. currentToken = null;
  627. addToken(new RETokenEnd(subIndex,((cflags & REG_MULTILINE) > 0) ? syntax.getLineSeparator() : null));
  628. }
  629. // MATCH-ANY-CHARACTER OPERATOR (except possibly newline and null)
  630. // .
  631. else if ((unit.ch == '.') && !(unit.bk || quot)) {
  632. addToken(currentToken);
  633. currentToken = new RETokenAny(subIndex,syntax.get(RESyntax.RE_DOT_NEWLINE) || ((cflags & REG_DOT_NEWLINE) > 0),syntax.get(RESyntax.RE_DOT_NOT_NULL));
  634. }
  635. // ZERO-OR-MORE REPEAT OPERATOR
  636. // *
  637. //
  638. // This method used to check "repeat.empty.token" to avoid such regexp
  639. // as "(a*)*", but now "repeat.empty.token" is allowed.
  640. else if ((unit.ch == '*') && !(unit.bk || quot)) {
  641. if (currentToken == null)
  642. throw new REException("quantifier (?*+{}) without preceding token",REException.REG_BADRPT,index);
  643. if (currentToken instanceof RETokenRepeated)
  644. throw new REException("attempted to repeat a token that is already repeated",REException.REG_BADRPT,index);
  645. if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
  646. throw new REException("repeated token is zero-width assertion",REException.REG_BADRPT,index);
  647. currentToken = setRepeated(currentToken,0,Integer.MAX_VALUE,index);
  648. }
  649. // ONE-OR-MORE REPEAT OPERATOR / POSSESSIVE MATCHING OPERATOR
  650. // + | \+ depending on RE_BK_PLUS_QM
  651. // not available if RE_LIMITED_OPS is set
  652. //
  653. // This method used to check "repeat.empty.token" to avoid such regexp
  654. // as "(a*)+", but now "repeat.empty.token" is allowed.
  655. else if ((unit.ch == '+') && !syntax.get(RESyntax.RE_LIMITED_OPS) && (!syntax.get(RESyntax.RE_BK_PLUS_QM) ^ (unit.bk || quot))) {
  656. if (currentToken == null)
  657. throw new REException("quantifier (?*+{}) without preceding token",REException.REG_BADRPT,index);
  658. // Check for possessive matching on RETokenRepeated
  659. if (currentToken instanceof RETokenRepeated) {
  660. RETokenRepeated tokenRep = (RETokenRepeated)currentToken;
  661. if (syntax.get(RESyntax.RE_POSSESSIVE_OPS) && !tokenRep.isPossessive() && !tokenRep.isStingy())
  662. tokenRep.makePossessive();
  663. else
  664. throw new REException("attempted to repeat a token that is already repeated",REException.REG_BADRPT,index);
  665. }
  666. else if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
  667. throw new REException("repeated token is zero-width assertion",REException.REG_BADRPT,index);
  668. else
  669. currentToken = setRepeated(currentToken,1,Integer.MAX_VALUE,index);
  670. }
  671. // ZERO-OR-ONE REPEAT OPERATOR / STINGY MATCHING OPERATOR
  672. // ? | \? depending on RE_BK_PLUS_QM
  673. // not available if RE_LIMITED_OPS is set
  674. // stingy matching if RE_STINGY_OPS is set and it follows a quantifier
  675. else if ((unit.ch == '?') && !syntax.get(RESyntax.RE_LIMITED_OPS) && (!syntax.get(RESyntax.RE_BK_PLUS_QM) ^ (unit.bk || quot))) {
  676. if (currentToken == null) throw new REException("quantifier (?*+{}) without preceding token",REException.REG_BADRPT,index);
  677. // Check for stingy matching on RETokenRepeated
  678. if (currentToken instanceof RETokenRepeated) {
  679. RETokenRepeated tokenRep = (RETokenRepeated)currentToken;
  680. if (syntax.get(RESyntax.RE_STINGY_OPS) && !tokenRep.isStingy() && !tokenRep.isPossessive())
  681. tokenRep.makeStingy();
  682. else
  683. throw new REException("attempted to repeat a token that is already repeated",REException.REG_BADRPT,index);
  684. }
  685. else if (currentToken instanceof RETokenWordBoundary || currentToken instanceof RETokenWordBoundary)
  686. throw new REException("repeated token is zero-width assertion",REException.REG_BADRPT,index);
  687. else
  688. currentToken = setRepeated(currentToken,0,1,index);
  689. }
  690. // OCTAL CHARACTER
  691. // \0377
  692. else if (unit.bk && (unit.ch == '0') && syntax.get(RESyntax.RE_OCTAL_CHAR)) {
  693. CharExpression ce = getCharExpression(pattern, index - 2, pLength, syntax);
  694. if (ce == null)
  695. throw new REException("invalid octal character", REException.REG_ESCAPE, index);
  696. index = index - 2 + ce.len;
  697. addToken(currentToken);
  698. currentToken = new RETokenChar(subIndex,ce.ch,insens);
  699. }
  700. // BACKREFERENCE OPERATOR
  701. // \1 \2 ... \9 and \10 \11 \12 ...
  702. // not available if RE_NO_BK_REFS is set
  703. // Perl recognizes \10, \11, and so on only if enough number of
  704. // parentheses have opened before it, otherwise they are treated
  705. // as aliases of \010, \011, ... (octal characters). In case of
  706. // Sun's JDK, octal character expression must always begin with \0.
  707. // We will do as JDK does. But FIXME, take a look at "(a)(b)\29".
  708. // JDK treats \2 as a back reference to the 2nd group because
  709. // there are only two groups. But in our poor implementation,
  710. // we cannot help but treat \29 as a back reference to the 29th group.
  711. else if (unit.bk && Character.isDigit(unit.ch) && !syntax.get(RESyntax.RE_NO_BK_REFS)) {
  712. addToken(currentToken);
  713. int numBegin = index - 1;
  714. int numEnd = pLength;
  715. for (int i = index; i < pLength; i++) {
  716. if (! Character.isDigit(pattern[i])) {
  717. numEnd = i;
  718. break;
  719. }
  720. }
  721. int num = parseInt(pattern, numBegin, numEnd-numBegin, 10);
  722. currentToken = new RETokenBackRef(subIndex,num,insens);
  723. index = numEnd;
  724. }
  725. // START OF STRING OPERATOR
  726. // \A if RE_STRING_ANCHORS is set
  727. else if (unit.bk && (unit.ch == 'A') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
  728. addToken(currentToken);
  729. currentToken = new RETokenStart(subIndex,null);
  730. }
  731. // WORD BREAK OPERATOR
  732. // \b if ????
  733. else if (unit.bk && (unit.ch == 'b') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
  734. addToken(currentToken);
  735. currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.BEGIN | RETokenWordBoundary.END, false);
  736. }
  737. // WORD BEGIN OPERATOR
  738. // \< if ????
  739. else if (unit.bk && (unit.ch == '<')) {
  740. addToken(currentToken);
  741. currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.BEGIN, false);
  742. }
  743. // WORD END OPERATOR
  744. // \> if ????
  745. else if (unit.bk && (unit.ch == '>')) {
  746. addToken(currentToken);
  747. currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.END, false);
  748. }
  749. // NON-WORD BREAK OPERATOR
  750. // \B if ????
  751. else if (unit.bk && (unit.ch == 'B') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
  752. addToken(currentToken);
  753. currentToken = new RETokenWordBoundary(subIndex, RETokenWordBoundary.BEGIN | RETokenWordBoundary.END, true);
  754. }
  755. // DIGIT OPERATOR
  756. // \d if RE_CHAR_CLASS_ESCAPES is set
  757. else if (unit.bk && (unit.ch == 'd') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
  758. addToken(currentToken);
  759. currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.DIGIT,insens,false);
  760. }
  761. // NON-DIGIT OPERATOR
  762. // \D
  763. else if (unit.bk && (unit.ch == 'D') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
  764. addToken(currentToken);
  765. currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.DIGIT,insens,true);
  766. }
  767. // NEWLINE ESCAPE
  768. // \n
  769. else if (unit.bk && (unit.ch == 'n')) {
  770. addToken(currentToken);
  771. currentToken = new RETokenChar(subIndex,'\n',false);
  772. }
  773. // RETURN ESCAPE
  774. // \r
  775. else if (unit.bk && (unit.ch == 'r')) {
  776. addToken(currentToken);
  777. currentToken = new RETokenChar(subIndex,'\r',false);
  778. }
  779. // WHITESPACE OPERATOR
  780. // \s if RE_CHAR_CLASS_ESCAPES is set
  781. else if (unit.bk && (unit.ch == 's') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
  782. addToken(currentToken);
  783. currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.SPACE,insens,false);
  784. }
  785. // NON-WHITESPACE OPERATOR
  786. // \S
  787. else if (unit.bk && (unit.ch == 'S') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
  788. addToken(currentToken);
  789. currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.SPACE,insens,true);
  790. }
  791. // TAB ESCAPE
  792. // \t
  793. else if (unit.bk && (unit.ch == 't')) {
  794. addToken(currentToken);
  795. currentToken = new RETokenChar(subIndex,'\t',false);
  796. }
  797. // ALPHANUMERIC OPERATOR
  798. // \w
  799. else if (unit.bk && (unit.ch == 'w') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
  800. addToken(currentToken);
  801. currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.ALNUM,insens,false);
  802. }
  803. // NON-ALPHANUMERIC OPERATOR
  804. // \W
  805. else if (unit.bk && (unit.ch == 'W') && syntax.get(RESyntax.RE_CHAR_CLASS_ESCAPES)) {
  806. addToken(currentToken);
  807. currentToken = new RETokenPOSIX(subIndex,RETokenPOSIX.ALNUM,insens,true);
  808. }
  809. // END OF STRING OPERATOR
  810. // \Z
  811. else if (unit.bk && (unit.ch == 'Z') && syntax.get(RESyntax.RE_STRING_ANCHORS)) {
  812. addToken(currentToken);
  813. currentToken = new RETokenEnd(subIndex,null);
  814. }
  815. // HEX CHARACTER, UNICODE CHARACTER
  816. // \x1B, \u1234
  817. else if ((unit.bk && (unit.ch == 'x') && syntax.get(RESyntax.RE_HEX_CHAR)) ||
  818. (unit.bk && (unit.ch == 'u') && syntax.get(RESyntax.RE_UNICODE_CHAR))) {
  819. CharExpression ce = getCharExpression(pattern, index - 2, pLength, syntax);
  820. if (ce == null)
  821. throw new REException("invalid hex character", REException.REG_ESCAPE, index);
  822. index = index - 2 + ce.len;
  823. addToken(currentToken);
  824. currentToken = new RETokenChar(subIndex,ce.ch,insens);
  825. }
  826. // NAMED PROPERTY
  827. // \p{prop}, \P{prop}
  828. else if ((unit.bk && (unit.ch == 'p') && syntax.get(RESyntax.RE_NAMED_PROPERTY)) ||
  829. (unit.bk && (unit.ch == 'P') && syntax.get(RESyntax.RE_NAMED_PROPERTY))) {
  830. NamedProperty np = getNamedProperty(pattern, index - 2, pLength);
  831. if (np == null)
  832. throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
  833. index = index - 2 + np.len;
  834. addToken(currentToken);
  835. currentToken = getRETokenNamedProperty(subIndex,np,insens,index);
  836. }
  837. // NON-SPECIAL CHARACTER (or escape to make literal)
  838. // c | \* for example
  839. else { // not a special character
  840. addToken(currentToken);
  841. currentToken = new RETokenChar(subIndex,unit.ch,insens);
  842. }
  843. } // end while
  844. // Add final buffered token and an EndSub marker
  845. addToken(currentToken);
  846. if (branches != null) {
  847. branches.addElement(new RE(firstToken,lastToken,numSubs,subIndex,minimumLength, maximumLength));
  848. branches.trimToSize(); // compact the Vector
  849. minimumLength = 0;
  850. maximumLength = 0;
  851. firstToken = lastToken = null;
  852. addToken(new RETokenOneOf(subIndex,branches,false));
  853. }
  854. else addToken(new RETokenEndSub(subIndex));
  855. }
  856. private static class ParseCharClassResult {
  857. RETokenOneOf token;
  858. int index;
  859. boolean returnAtAndOperator = false;
  860. }
  861. /**
  862. * Parse [...] or [^...] and make an RETokenOneOf instance.
  863. * @param subIndex subIndex to be given to the created RETokenOneOf instance.
  864. * @param pattern Input array of characters to be parsed.
  865. * @param index Index pointing to the character next to the beginning '['.
  866. * @param pLength Limit of the input array.
  867. * @param cflags Compilation flags used to parse the pattern.
  868. * @param pflags Flags that affect the behavior of this method.
  869. * @param syntax Syntax used to parse the pattern.
  870. */
  871. private static ParseCharClassResult parseCharClass(int subIndex,
  872. char[] pattern, int index,
  873. int pLength, int cflags, RESyntax syntax, int pflags)
  874. throws REException {
  875. boolean insens = ((cflags & REG_ICASE) > 0);
  876. Vector options = new Vector();
  877. Vector addition = new Vector();
  878. boolean additionAndAppeared = false;
  879. final int RETURN_AT_AND = 0x01;
  880. boolean returnAtAndOperator = ((pflags & RETURN_AT_AND) != 0);
  881. boolean negative = false;
  882. char ch;
  883. char lastChar = 0;
  884. boolean lastCharIsSet = false;
  885. if (index == pLength) throw new REException("unmatched bracket",REException.REG_EBRACK,index);
  886. // Check for initial caret, negation
  887. if ((ch = pattern[index]) == '^') {
  888. negative = true;
  889. if (++index == pLength) throw new REException("unexpected end of character class",REException.REG_EBRACK,index);
  890. ch = pattern[index];
  891. }
  892. // Check for leading right bracket literal
  893. if (ch == ']') {
  894. lastChar = ch; lastCharIsSet = true;
  895. if (++index == pLength) throw new REException("unexpected end of character class",REException.REG_EBRACK,index);
  896. }
  897. while ((ch = pattern[index++]) != ']') {
  898. if ((ch == '-') && (lastCharIsSet)) {
  899. if (index == pLength) throw new REException("unexpected end of character class",REException.REG_EBRACK,index);
  900. if ((ch = pattern[index]) == ']') {
  901. options.addElement(new RETokenChar(subIndex,lastChar,insens));
  902. lastChar = '-';
  903. } else {
  904. if ((ch == '\\') && syntax.get(RESyntax.RE_BACKSLASH_ESCAPE_IN_LISTS)) {
  905. CharExpression ce = getCharExpression(pattern, index, pLength, syntax);
  906. if (ce == null)
  907. throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
  908. ch = ce.ch;
  909. index = index + ce.len - 1;
  910. }
  911. options.addElement(new RETokenRange(subIndex,lastChar,ch,insens));
  912. lastChar = 0; lastCharIsSet = false;
  913. index++;
  914. }
  915. } else if ((ch == '\\') && syntax.get(RESyntax.RE_BACKSLASH_ESCAPE_IN_LISTS)) {
  916. if (index == pLength) throw new REException("unexpected end of character class",REException.REG_EBRACK,index);
  917. int posixID = -1;
  918. boolean negate = false;
  919. char asciiEsc = 0;
  920. boolean asciiEscIsSet = false;
  921. NamedProperty np = null;
  922. if (("dswDSW".indexOf(pattern[index]) != -1) && syntax.get(RESyntax.RE_CHAR_CLASS_ESC_IN_LISTS)) {
  923. switch (pattern[index]) {
  924. case 'D':
  925. negate = true;
  926. case 'd':
  927. posixID = RETokenPOSIX.DIGIT;
  928. break;
  929. case 'S':
  930. negate = true;
  931. case 's':
  932. posixID = RETokenPOSIX.SPACE;
  933. break;
  934. case 'W':
  935. negate = true;
  936. case 'w':
  937. posixID = RETokenPOSIX.ALNUM;
  938. break;
  939. }
  940. }
  941. if (("pP".indexOf(pattern[index]) != -1) && syntax.get(RESyntax.RE_NAMED_PROPERTY)) {
  942. np = getNamedProperty(pattern, index - 1, pLength);
  943. if (np == null)
  944. throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
  945. index = index - 1 + np.len - 1;
  946. }
  947. else {
  948. CharExpression ce = getCharExpression(pattern, index - 1, pLength, syntax);
  949. if (ce == null)
  950. throw new REException("invalid escape sequence", REException.REG_ESCAPE, index);
  951. asciiEsc = ce.ch; asciiEscIsSet = true;
  952. index = index - 1 + ce.len - 1;
  953. }
  954. if (lastCharIsSet) options.addElement(new RETokenChar(subIndex,lastChar,insens));
  955. if (posixID != -1) {
  956. options.addElement(new RETokenPOSIX(subIndex,posixID,insens,negate));
  957. } else if (np != null) {
  958. options.addElement(getRETokenNamedProperty(subIndex,np,insens,index));
  959. } else if (asciiEscIsSet) {
  960. lastChar = asciiEsc; lastCharIsSet = true;
  961. } else {
  962. lastChar = pattern[index]; lastCharIsSet = true;
  963. }
  964. ++index;
  965. } else if ((ch == '[') && (syntax.get(RESyntax.RE_CHAR_CLASSES)) && (index < pLength) && (pattern[index] == ':')) {
  966. StringBuffer posixSet = new StringBuffer();
  967. index = getPosixSet(pattern,index+1,posixSet);
  968. int posixId = RETokenPOSIX.intValue(posixSet.toString());
  969. if (posixId != -1)
  970. options.addElement(new RETokenPOSIX(subIndex,posixId,insens,false));
  971. } else if ((ch == '[') && (syntax.get(RESyntax.RE_NESTED_CHARCLASS))) {
  972. ParseCharClassResult result = parseCharClass(
  973. subIndex, pattern, index, pLength, cflags, syntax, 0);
  974. addition.addElement(result.token);
  975. addition.addElement("|");
  976. index = result.index;
  977. } else if ((ch == '&') &&
  978. (syntax.get(RESyntax.RE_NESTED_CHARCLASS)) &&
  979. (index < pLength) && (pattern[index] == '&')) {
  980. if (returnAtAndOperator) {
  981. ParseCharClassResult result = new ParseCharClassResult();
  982. options.trimToSize();
  983. if (additionAndAppeared) addition.addElement("&");
  984. if (addition.size() == 0) addition = null;
  985. result.token = new RETokenOneOf(subIndex,
  986. options, addition, negative);
  987. result.index = index - 1;
  988. result.returnAtAndOperator = true;
  989. return result;
  990. }
  991. // The precedence of the operator "&&" is the lowest.
  992. // So we postpone adding "&" until other elements
  993. // are added. And we insert Boolean.FALSE at the
  994. // beginning of the list of tokens following "&&".
  995. // So, "&&[a-b][k-m]" will be stored in the Vecter
  996. // addition in this order:
  997. // Boolean.FALSE, [a-b], "|", [k-m], "|", "&"
  998. if (additionAndAppeared) addition.addElement("&");
  999. addition.addElement(Boolean.FALSE);
  1000. additionAndAppeared = true;
  1001. // The part on which "&&" operates may be either
  1002. // (1) explicitly enclosed by []
  1003. // or
  1004. // (2) not enclosed by [] and terminated by the
  1005. // next "&&" or the end of the character list.
  1006. // Let the preceding else if block do the case (1).
  1007. // We must do something in case of (2).
  1008. if ((index + 1 < pLength) && (pattern[index + 1] != '[')) {
  1009. ParseCharClassResult result = parseCharClass(
  1010. subIndex, pattern, index+1, pLength, cflags, syntax,
  1011. RETURN_AT_AND);
  1012. addition.addElement(result.token);
  1013. addition.addElement("|");
  1014. // If the method returned at the next "&&", it is OK.
  1015. // Otherwise we have eaten the mark of the end of this
  1016. // character list "]". In this case we must give back
  1017. // the end mark.
  1018. index = (result.returnAtAndOperator ?
  1019. result.index: result.index - 1);
  1020. }
  1021. } else {
  1022. if (lastCharIsSet) options.addElement(new RETokenChar(subIndex,lastChar,insens));
  1023. lastChar = ch; lastCharIsSet = true;
  1024. }
  1025. if (index == pLength) throw new REException("unexpected end of character class",REException.REG_EBRACK,index);
  1026. } // while in list
  1027. // Out of list, index is one past ']'
  1028. if (lastCharIsSet) options.addElement(new RETokenChar(subIndex,lastChar,insens));
  1029. ParseCharClassResult result = new ParseCharClassResult();
  1030. // Create a new RETokenOneOf
  1031. options.trimToSize();
  1032. if (additionAndAppeared) addition.addElement("&");
  1033. if (addition.size() == 0) addition = null;
  1034. result.token = new RETokenOneOf(subIndex,options, addition, negative);
  1035. result.index = index;
  1036. return result;
  1037. }
  1038. private static int getCharUnit(char[] input, int index, CharUnit unit, boolean quot) throws REException {
  1039. unit.ch = input[index++];
  1040. unit.bk = (unit.ch == '\\'
  1041. && (!quot || index >= input.length || input[index] == 'E'));
  1042. if (unit.bk)
  1043. if (index < input.length)
  1044. unit.ch = input[index++];
  1045. else throw new REException("backslash at end of pattern",REException.REG_ESCAPE,index);
  1046. return index;
  1047. }
  1048. private static int parseInt(char[] input, int pos, int len, int radix) {
  1049. int ret = 0;
  1050. for (int i = pos; i < pos + len; i++) {
  1051. ret = ret * radix + Character.digit(input[i], radix);
  1052. }
  1053. return ret;
  1054. }
  1055. /**
  1056. * This class represents various expressions for a character.
  1057. * "a" : 'a' itself.
  1058. * "\0123" : Octal char 0123
  1059. * "\x1b" : Hex char 0x1b
  1060. * "\u1234" : Unicode char \u1234
  1061. */
  1062. private static class CharExpression {
  1063. /** character represented by this expression */
  1064. char ch;
  1065. /** String expression */
  1066. String expr;
  1067. /** length of this expression */
  1068. int len;
  1069. public String toString() { return expr; }
  1070. }
  1071. private static CharExpression getCharExpression(char[] input, int pos, int lim,
  1072. RESyntax syntax) {
  1073. CharExpression ce = new CharExpression();
  1074. char c = input[pos];
  1075. if (c == '\\') {
  1076. if (pos + 1 >= lim) return null;
  1077. c = input[pos + 1];
  1078. switch(c) {
  1079. case 't':
  1080. ce.ch = '\t';
  1081. ce.len = 2;
  1082. break;
  1083. case 'n':
  1084. ce.ch = '\n';
  1085. ce.len = 2;
  1086. break;
  1087. case 'r':
  1088. ce.ch = '\r';
  1089. ce.len = 2;
  1090. break;
  1091. case 'x':
  1092. case 'u':
  1093. if ((c == 'x' && syntax.get(RESyntax.RE_HEX_CHAR)) ||
  1094. (c == 'u' && syntax.get(RESyntax.RE_UNICODE_CHAR))) {
  1095. int l = 0;
  1096. int expectedLength = (c == 'x' ? 2 : 4);
  1097. for (int i = pos + 2; i < pos + 2 + expectedLength; i++) {
  1098. if (i >= lim) break;
  1099. if (!((input[i] >= '0' && input[i] <= '9') ||
  1100. (input[i] >= 'A' && input[i] <= 'F') ||
  1101. (input[i] >= 'a' && input[i] <= 'f')))
  1102. break;
  1103. l++;
  1104. }
  1105. if (l != expectedLength) return null;
  1106. ce.ch = (char)(parseInt(input, pos + 2, l, 16));
  1107. ce.len = l + 2;
  1108. }
  1109. else {
  1110. ce.ch = c;
  1111. ce.len = 2;
  1112. }
  1113. break;
  1114. case '0':
  1115. if (syntax.get(RESyntax.RE_OCTAL_CHAR)) {
  1116. int l = 0;
  1117. for (int i = pos + 2; i < pos + 2 + 3; i++) {
  1118. if (i >= lim) break;
  1119. if (input[i] < '0' || input[i] > '7') break;
  1120. l++;
  1121. }
  1122. if (l == 3 && input[pos + 2] > '3') l--;
  1123. if (l <= 0) return null;
  1124. ce.ch = (char)(parseInt(input, pos + 2, l, 8));
  1125. ce.len = l + 2;
  1126. }
  1127. else {
  1128. ce.ch = c;
  1129. ce.len = 2;
  1130. }
  1131. break;
  1132. default:
  1133. ce.ch = c;
  1134. ce.len = 2;
  1135. break;
  1136. }
  1137. }
  1138. else {
  1139. ce.ch = input[pos];
  1140. ce.len = 1;
  1141. }
  1142. ce.expr = new String(input, pos, ce.len);
  1143. return ce;
  1144. }
  1145. /**
  1146. * This class represents a substring in a pattern string expressing
  1147. * a named property.
  1148. * "\pA" : Property named "A"
  1149. * "\p{prop}" : Property named "prop"
  1150. * "\PA" : Property named "A" (Negated)
  1151. * "\P{prop}" : Property named "prop" (Negated)
  1152. */
  1153. private static class NamedProperty {
  1154. /** Property name */
  1155. String name;
  1156. /** Negated or not */
  1157. boolean negate;
  1158. /** length of this expression */
  1159. int len;
  1160. }
  1161. private static NamedProperty getNamedProperty(char[] input, int pos, int lim) {
  1162. NamedProperty np = new NamedProperty();
  1163. char c = input[pos];
  1164. if (c == '\\') {
  1165. if (++pos >= lim) return null;
  1166. c = input[pos++];
  1167. switch(c) {
  1168. case 'p':
  1169. np.negate = false;
  1170. break;
  1171. case 'P':
  1172. np.negate = true;
  1173. break;
  1174. default:
  1175. return null;
  1176. }
  1177. c = input[pos++];
  1178. if (c == '{') {
  1179. int p = -1;
  1180. for (int i = pos; i < lim; i++) {
  1181. if (input[i] == '}') {
  1182. p = i;
  1183. break;
  1184. }
  1185. }
  1186. if (p < 0) return null;
  1187. int len = p - pos;
  1188. np.name = new String(input, pos, len);
  1189. np.len = len + 4;
  1190. }
  1191. else {
  1192. np.name = new String(input, pos - 1, 1);
  1193. np.len = 3;
  1194. }
  1195. return np;
  1196. }
  1197. else return null;
  1198. }
  1199. private static RETokenNamedProperty getRETokenNamedProperty(
  1200. int subIndex, NamedProperty np, boolean insens, int index)
  1201. throws REException {
  1202. try {
  1203. return new RETokenNamedProperty(subIndex, np.name, insens, np.negate);
  1204. }
  1205. catch (REException e) {
  1206. REException ree;
  1207. ree = new REException(e.getMessage(), REException.REG_ESCAPE, index);
  1208. // ree.initCause(e);
  1209. throw ree;
  1210. }
  1211. }
  1212. /**
  1213. * Checks if the regular expression matches the input in its entirety.
  1214. *
  1215. * @param input The input text.
  1216. */
  1217. public boolean isMatch(Object input) {
  1218. return isMatch(input,0,0);
  1219. }
  1220. /**
  1221. * Checks if the input string, starting from index, is an exact match of
  1222. * this regular expression.
  1223. *
  1224. * @param input The input text.
  1225. * @param index The offset index at which the search should be begin.
  1226. */
  1227. public boolean isMatch(Object input,int index) {
  1228. return isMatch(input,index,0);
  1229. }
  1230. /**
  1231. * Checks if the input, starting from index and using the specified
  1232. * execution flags, is an exact match of this regular expression.
  1233. *
  1234. * @param input The input text.
  1235. * @param index The offset index at which the search should be begin.
  1236. * @param eflags The logical OR of any execution flags above.
  1237. */
  1238. public boolean isMatch(Object input,int index,int eflags) {
  1239. return isMatchImpl(makeCharIndexed(input,index),index,eflags);
  1240. }
  1241. private boolean isMatchImpl(CharIndexed input, int index, int eflags) {
  1242. if (firstToken == null) // Trivial case
  1243. return (input.charAt(0) == CharIndexed.OUT_OF_BOUNDS);
  1244. REMatch m = new REMatch(numSubs, index, eflags);
  1245. if (firstToken.match(input, m)) {
  1246. while (m != null) {
  1247. if (input.charAt(m.index) == CharIndexed.OUT_OF_BOUNDS) {
  1248. return true;
  1249. }
  1250. m = m.next;
  1251. }
  1252. }
  1253. return false;
  1254. }
  1255. /**
  1256. * Returns the maximum number of subexpressions in this regular expression.
  1257. * If the expression contains branches, the value returned will be the
  1258. * maximum subexpressions in any of the branches.
  1259. */
  1260. public int getNumSubs() {
  1261. return numSubs;
  1262. }
  1263. // Overrides REToken.setUncle
  1264. void setUncle(REToken uncle) {
  1265. if (lastToken != null) {
  1266. lastToken.setUncle(uncle);
  1267. } else super.setUncle(uncle); // to deal with empty subexpressions
  1268. }
  1269. // Overrides REToken.chain
  1270. boolean chain(REToken next) {
  1271. super.chain(next);
  1272. setUncle(next);
  1273. return true;
  1274. }
  1275. /**
  1276. * Returns the minimum number of characters that could possibly
  1277. * constitute a match of this regular expression.
  1278. */
  1279. public int getMinimumLength() {
  1280. return minimumLength;
  1281. }
  1282. public int getMaximumLength() {
  1283. return maximumLength;
  1284. }
  1285. /**
  1286. * Returns an array of all matches found in the input.
  1287. *
  1288. * If the regular expression allows the empty string to match, it w…