Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    *
    * This code is free software; you can redistribute it and/or modify it
    * under the terms of the GNU General Public License version 2 only, as
    * published by the Free Software Foundation.  Oracle designates this
    * particular file as subject to the "Classpath" exception as provided
    * by Oracle in the LICENSE file that accompanied this code.
   *
   * This code is distributed in the hope that it will be useful, but WITHOUT
   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   * version 2 for more details (a copy is included in the LICENSE file that
   * accompanied this code).
   *
   * You should have received a copy of the GNU General Public License version
   * 2 along with this work; if not, write to the Free Software Foundation,
   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   *
   * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
   * or visit www.oracle.com if you need additional information or have any
   * questions.
   */
  
  package java.util.regex;
  
  import java.util.Locale;
  import java.util.Map;
  import java.util.HashMap;
  import java.util.Arrays;


A compiled representation of a regular expression.

A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary java.lang.CharSequence against the regular expression. All of the state involved in performing a match resides in the matcher, so many matchers can share the same pattern.

A typical invocation sequence is thus

 Pattern p = Pattern.compile("a*b");
 Matcher m = p.matcher("aaaaab");
 boolean b = m.matches();

A matches method is defined by this class as a convenience for when a regular expression is used just once. This method compiles an expression and matches an input sequence against it in a single invocation. The statement

 boolean b = Pattern.matches("a*b", "aaaaab");
is equivalent to the three statements above, though for repeated matches it is less efficient since it does not allow the compiled pattern to be reused.

Instances of this class are immutable and are safe for use by multiple concurrent threads. Instances of the Matcher class are not safe for such use.

Summary of regular-expression constructs

*
ConstructMatches
 
Characters
xThe character x
\\The backslash character
\0nThe character with octal value 0n (0 <= n <= 7)
\0nnThe character with octal value 0nn (0 <= n <= 7)
\0mnnThe character with octal value 0mnn (0 <= m <= 3, 0 <= n <= 7)
\xhhThe character with hexadecimal value 0xhh
\uhhhhThe character with hexadecimal value 0xhhhh
\x{h...h}The character with hexadecimal value 0xh...h (Character.MIN_CODE_POINT  <= 0xh...h <=&nbsp Character.MAX_CODE_POINT)
\tThe tab character ('\u0009')
\nThe newline (line feed) character ('\u000A')
\rThe carriage-return character ('\u000D')
\fThe form-feed character ('\u000C')
\aThe alert (bell) character ('\u0007')
\eThe escape character ('\u001B')
\cxThe control character corresponding to x
 
Character classes
[abc]a, b, or c (simple class)
[^abc]Any character except a, b, or c (negation)
[a-zA-Z]a through z or A through Z, inclusive (range)
[a-d[m-p]]a through d, or m through p: [a-dm-p] (union)
[a-z&&[def]]d, e, or f (intersection)
[a-z&&[^bc]]a through z, except for b and c: [ad-z] (subtraction)
[a-z&&[^m-p]]a through z, and not m through p: [a-lq-z](subtraction)
 
Predefined character classes
.Any character (may or may not match line terminators)
\dA digit: [0-9]
\DA non-digit: [^0-9]
\sA whitespace character: [ \t\n\x0B\f\r]
\SA non-whitespace character: [^\s]
\wA word character: [a-zA-Z_0-9]
\WA non-word character: [^\w]
 
POSIX character classes (US-ASCII only)
\p{Lower}A lower-case alphabetic character: [a-z]
\p{Upper}An upper-case alphabetic character:[A-Z]
\p{ASCII}All ASCII:[\x00-\x7F]
\p{Alpha}An alphabetic character:[\p{Lower}\p{Upper}]
\p{Digit}A decimal digit: [0-9]
\p{Alnum}An alphanumeric character:[\p{Alpha}\p{Digit}]
\p{Punct}Punctuation: One of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
\p{Graph}A visible character: [\p{Alnum}\p{Punct}]
\p{Print}A printable character: [\p{Graph}\x20]
\p{Blank}A space or a tab: [ \t]
\p{Cntrl}A control character: [\x00-\x1F\x7F]
\p{XDigit}A hexadecimal digit: [0-9a-fA-F]
\p{Space}A whitespace character: [ \t\n\x0B\f\r]
 
java.lang.Character classes (simple java character type)
\p{javaLowerCase}Equivalent to java.lang.Character.isLowerCase()
\p{javaUpperCase}Equivalent to java.lang.Character.isUpperCase()
\p{javaWhitespace}Equivalent to java.lang.Character.isWhitespace()
\p{javaMirrored}Equivalent to java.lang.Character.isMirrored()
 
Classes for Unicode scripts, blocks, categories and binary properties
\p{IsLatin}A Latin script character (script)
\p{InGreek}A character in the Greek block (block)
\p{Lu}An uppercase letter (category)
\p{IsAlphabetic}An alphabetic character (binary property)
\p{Sc}A currency symbol
\P{InGreek}Any character except one in the Greek block (negation)
[\p{L}&&[^\p{Lu}]] Any letter except an uppercase letter (subtraction)
 
Boundary matchers
^The beginning of a line
$The end of a line
\bA word boundary
\BA non-word boundary
\AThe beginning of the input
\GThe end of the previous match
\ZThe end of the input but for the final terminator, if any
\zThe end of the input
 
Greedy quantifiers
X?X, once or not at all
X*X, zero or more times
X+X, one or more times
X{n}X, exactly n times
X{n,}X, at least n times
X{n,m}X, at least n but not more than m times
 
Reluctant quantifiers
X??X, once or not at all
X*?X, zero or more times
X+?X, one or more times
X{n}?X, exactly n times
X{n,}?X, at least n times
X{n,m}?X, at least n but not more than m times
 
Possessive quantifiers
X?+X, once or not at all
X*+X, zero or more times
X++X, one or more times
X{n}+X, exactly n times
X{n,}+X, at least n times
X{n,m}+X, at least n but not more than m times
 
Logical operators
XYX followed by Y
X|YEither X or Y
(X)X, as a capturing group
 
Back references
\nWhatever the nth capturing group matched
\k<name>Whatever the named-capturing group "name" matched
 
Quotation
\Nothing, but quotes the following character
\QNothing, but quotes all characters until \E
\ENothing, but ends quoting started by \Q
 
Special constructs (named-capturing and non-capturing)
(?<name>X)X, as a named-capturing group
(?:X)X, as a non-capturing group
(?idmsuxU-idmsuxU) Nothing, but turns match flags i d m s u x U on - off
(?idmsux-idmsux:X)  X, as a non-capturing group with the given flags i d m s u x on - off
(?=X)X, via zero-width positive lookahead
(?!X)X, via zero-width negative lookahead
(?<=X)X, via zero-width positive lookbehind
(?<!X)X, via zero-width negative lookbehind
(?>X)X, as an independent, non-capturing group

Backslashes, escapes, and quoting

The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.

It is an error to use a backslash prior to any alphabetic character that does not denote an escaped construct; these are reserved for future extensions to the regular-expression language. A backslash may be used prior to a non-alphabetic character regardless of whether that character is part of an unescaped construct.

Backslashes within string literals in Java source code are interpreted as required by The Java™ Language Specification as either Unicode escapes (section 3.3) or other character escapes (section 3.10.6) It is therefore necessary to double backslashes in string literals that represent regular expressions to protect them from interpretation by the Java bytecode compiler. The string literal "\b", for example, matches a single backspace character when interpreted as a regular expression, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and leads to a compile-time error; in order to match the string (hello) the string literal "\\(hello\\)" must be used.

Character Classes

Character classes may appear within other character classes, and may be composed by the union operator (implicit) and the intersection operator (&&). The union operator denotes a class that contains every character that is in at least one of its operand classes. The intersection operator denotes a class that contains every character that is in both of its operand classes.

The precedence of character-class operators is as follows, from highest to lowest:

1    Literal escape    \x
2    Grouping[...]
3    Rangea-z
4    Union[a-e][i-u]
5    Intersection[a-z&&[aeiou]]

Note that a different set of metacharacters are in effect inside a character class than outside a character class. For instance, the regular expression . loses its special meaning inside a character class, while the expression - becomes a range forming metacharacter.

Line terminators

A line terminator is a one- or two-character sequence that marks the end of a line of the input character sequence. The following are recognized as line terminators:

  • A newline (line feed) character ('\n'),
  • A carriage-return character followed immediately by a newline character ("\r\n"),
  • A standalone carriage-return character ('\r'),
  • A next-line character ('\u0085'),
  • A line-separator character ('\u2028'), or
  • A paragraph-separator character ('\u2029).

If UNIX_LINES mode is activated, then the only line terminators recognized are newline characters.

The regular expression . matches any character except a line terminator unless the DOTALL flag is specified.

By default, the regular expressions ^ and $ ignore line terminators and only match at the beginning and the end, respectively, of the entire input sequence. If MULTILINE mode is activated then ^ matches at the beginning of input and after any line terminator except at the end of input. When in MULTILINE mode $ matches just before a line terminator or the end of the input sequence.

Groups and capturing

Group number

Capturing groups are numbered by counting their opening parentheses from left to right. In the expression ((A)(B(C))), for example, there are four such groups:

1    ((A)(B(C)))
2    (A)
3    (B(C))
4    (C)

Group zero always stands for the entire expression.

Capturing groups are so named because, during a match, each subsequence of the input sequence that matches such a group is saved. The captured subsequence may be used later in the expression, via a back reference, and may also be retrieved from the matcher once the match operation is complete.

Group name

A capturing group can also be assigned a "name", a named-capturing group, and then be back-referenced later by the "name". Group names are composed of the following characters. The first character must be a letter.

  • The uppercase letters 'A' through 'Z' ('\u0041' through '\u005a'),
  • The lowercase letters 'a' through 'z' ('\u0061' through '\u007a'),
  • The digits '0' through '9' ('\u0030' through '\u0039'),

A named-capturing group is still numbered as described in Group number.

The captured input associated with a group is always the subsequence that the group most recently matched. If a group is evaluated a second time because of quantification then its previously-captured value, if any, will be retained if the second evaluation fails. Matching the string "aba" against the expression (a(b)?)+, for example, leaves group two set to "b". All captured input is discarded at the beginning of each match.

Groups beginning with (? are either pure, non-capturing groups that do not capture text and do not count towards the group total, or named-capturing group.

Unicode support

This class is in conformance with Level 1 of Unicode Technical Standard #18: Unicode Regular Expression, plus RL2.1 Canonical Equivalents.

Unicode escape sequences such as \u2014 in Java source code are processed as described in section 3.3 of The Java™ Language Specification. Such escape sequences are also implemented directly by the regular-expression parser so that Unicode escapes can be used in expressions that are read from files or from the keyboard. Thus the strings "\u2014" and "\\u2014", while not equal, compile into the same pattern, which matches the character with hexadecimal value 0x2014.

A Unicode character can also be represented in a regular-expression by using its Hex notation(hexadecimal code point value) directly as described in construct \x{...}, for example a supplementary character U+2011F can be specified as \x{2011F}, instead of two consecutive Unicode escape sequences of the surrogate pair \uD840\uDD1F.

Unicode scripts, blocks, categories and binary properties are written with the \p and \P constructs as in Perl. \p{prop} matches if the input has the property prop, while \P{prop} does not match if the input has that property.

Scripts, blocks, categories and binary properties can be used both inside and outside of a character class.

Scripts are specified either with the prefix Is, as in IsHiragana, or by using the script keyword (or its short form sc)as in script=Hiragana or sc=Hiragana.

The script names supported by Pattern are the valid script names accepted and defined by UnicodeScript.forName.

Blocks are specified with the prefix In, as in InMongolian, or by using the keyword block (or its short form blk) as in block=Mongolian or blk=Mongolian.

The block names supported by Pattern are the valid block names accepted and defined by UnicodeBlock.forName.

Categories may be specified with the optional prefix Is: Both \p{L} and \p{IsL} denote the category of Unicode letters. Same as scripts and blocks, categories can also be specified by using the keyword general_category (or its short form gc) as in general_category=Lu or gc=Lu.

The supported categories are those of The Unicode Standard in the version specified by the Character class. The category names are those defined in the Standard, both normative and informative.

Binary properties are specified with the prefix Is, as in IsAlphabetic. The supported binary properties by Pattern are

  • Alphabetic
  • Ideographic
  • Letter
  • Lowercase
  • Uppercase
  • Titlecase
  • Punctuation
  • Control
  • White_Space
  • Digit
  • Hex_Digit
  • Noncharacter_Code_Point
  • Assigned

Predefined Character classes and POSIX character classes are in conformance with the recommendation of Annex C: Compatibility Properties of Unicode Regular Expression , when UNICODE_CHARACTER_CLASS flag is specified.

ClassesMatches
\p{Lower}A lowercase character:\p{IsLowercase}
\p{Upper}An uppercase character:\p{IsUppercase}
\p{ASCII}All ASCII:[\x00-\x7F]
\p{Alpha}An alphabetic character:\p{IsAlphabetic}
\p{Digit}A decimal digit character:p{IsDigit}
\p{Alnum}An alphanumeric character:[\p{IsAlphabetic}\p{IsDigit}]
\p{Punct}A punctuation character:p{IsPunctuation}
\p{Graph}A visible character: [^\p{IsWhite_Space}\p{gc=Cc}\p{gc=Cs}\p{gc=Cn}]
\p{Print}A printable character: [\p{Graph}\p{Blank}&&[^\p{Cntrl}]]
\p{Blank}A space or a tab: [\p{IsWhite_Space}&&[^\p{gc=Zl}\p{gc=Zp}\x0a\x0b\x0c\x0d\x85]]
\p{Cntrl}A control character: \p{gc=Cc}
\p{XDigit}A hexadecimal digit: [\p{gc=Nd}\p{IsHex_Digit}]
\p{Space}A whitespace character:\p{IsWhite_Space}
\dA digit: \p{IsDigit}
\DA non-digit: [^\d]
\sA whitespace character: \p{IsWhite_Space}
\SA non-whitespace character: [^\s]
\wA word character: [\p{Alpha}\p{gc=Mn}\p{gc=Me}\p{gc=Mc}\p{Digit}\p{gc=Pc}]
\WA non-word character: [^\w]

Categories that behave like the java.lang.Character boolean ismethodname methods (except for the deprecated ones) are available through the same \p{prop} syntax where the specified property has the name javamethodname.

Comparison to Perl 5

The Pattern engine performs traditional NFA-based matching with ordered alternation as occurs in Perl 5.

Perl constructs not supported by this class:

  • Predefined character classes (Unicode character)

    \h    A horizontal whitespace

    \H    A non horizontal whitespace

    \v    A vertical whitespace

    \V    A non vertical whitespace

    \R    Any Unicode linebreak sequence \u005cu000D\u005cu000A|[\u005cu000A\u005cu000B\u005cu000C\u005cu000D\u005cu0085\u005cu2028\u005cu2029]

    \X    Match Unicode extended grapheme cluster

  • The backreference constructs, \g{n} for the nthcapturing group and \g{name} for named-capturing group.

  • The named character construct, \N{name} for a Unicode character by its name.

  • The conditional constructs (?(condition)X) and (?(condition)X|Y),

  • The embedded code constructs (?{code}) and (??{code}),

  • The embedded comment syntax (?#comment), and

  • The preprocessing operations \l \u, \L, and \U.

Constructs supported by this class but not by Perl:

  • Character-class union and intersection as described above.

Notable differences from Perl:

  • In Perl, \1 through \9 are always interpreted as back references; a backslash-escaped number greater than 9 is treated as a back reference if at least that many subexpressions exist, otherwise it is interpreted, if possible, as an octal escape. In this class octal escapes must always begin with a zero. In this class, \1 through \9 are always interpreted as back references, and a larger number is accepted as a back reference if at least that many subexpressions exist at that point in the regular expression, otherwise the parser will drop digits until the number is smaller or equal to the existing number of groups or it is one digit.

  • Perl uses the g flag to request a match that resumes where the last match left off. This functionality is provided implicitly by the Matcher class: Repeated invocations of the Matcher.find() method will resume where the last match left off, unless the matcher is reset.

  • In Perl, embedded flags at the top level of an expression affect the whole expression. In this class, embedded flags always take effect at the point at which they appear, whether they are at the top level or within a group; in the latter case, flags are restored at the end of the group just as in Perl.

For a more precise description of the behavior of regular expression constructs, please see Mastering Regular Expressions, 3nd Edition, Jeffrey E. F. Friedl, O'Reilly and Associates, 2006.

Author(s):
Mike McCloskey
Mark Reinhold
JSR-51 Expert Group
Since:
1.4
See also:
java.lang.String.split(java.lang.String,int)
java.lang.String.split(java.lang.String)
Spec:
JSR-51

 
 
 public final class Pattern
     implements java.io.Serializable
 {

    
Regular expression modifier values. Instead of being passed as arguments, they can also be passed as inline modifiers. For example, the following statements have the same effect.
 RegExp r1 = RegExp.compile("abc", Pattern.I|Pattern.M);
 RegExp r2 = RegExp.compile("(?im)abc", 0);
 
The flags are duplicated so that the familiar Perl match flag names are available.
 

    
Enables Unix lines mode.

In this mode, only the '\n' line terminator is recognized in the behavior of ., ^, and $.

Unix lines mode can also be enabled via the embedded flag expression (?d).

 
     public static final int UNIX_LINES = 0x01;

    
Enables case-insensitive matching.

By default, case-insensitive matching assumes that only characters in the US-ASCII charset are being matched. Unicode-aware case-insensitive matching can be enabled by specifying the UNICODE_CASE flag in conjunction with this flag.

Case-insensitive matching can also be enabled via the embedded flag expression (?i).

Specifying this flag may impose a slight performance penalty.

 
     public static final int CASE_INSENSITIVE = 0x02;

    
Permits whitespace and comments in pattern.

In this mode, whitespace is ignored, and embedded comments starting with # are ignored until the end of a line.

Comments mode can also be enabled via the embedded flag expression (?x).

 
     public static final int COMMENTS = 0x04;

    
Enables multiline mode.

In multiline mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the input sequence. By default these expressions only match at the beginning and the end of the entire input sequence.

Multiline mode can also be enabled via the embedded flag expression (?m).

 
     public static final int MULTILINE = 0x08;

    
Enables literal parsing of the pattern.

When this flag is specified then the input string that specifies the pattern is treated as a sequence of literal characters. Metacharacters or escape sequences in the input sequence will be given no special meaning.

The flags CASE_INSENSITIVE and UNICODE_CASE retain their impact on matching when used in conjunction with this flag. The other flags become superfluous.

There is no embedded flag character for enabling literal parsing.

Since:
1.5
 
     public static final int LITERAL = 0x10;

    
Enables dotall mode.

In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators.

Dotall mode can also be enabled via the embedded flag expression (?s). (The s is a mnemonic for "single-line" mode, which is what this is called in Perl.)

 
     public static final int DOTALL = 0x20;

    
Enables Unicode-aware case folding.

When this flag is specified then case-insensitive matching, when enabled by the CASE_INSENSITIVE flag, is done in a manner consistent with the Unicode Standard. By default, case-insensitive matching assumes that only characters in the US-ASCII charset are being matched.

Unicode-aware case folding can also be enabled via the embedded flag expression (?u).

Specifying this flag may impose a performance penalty.

 
     public static final int UNICODE_CASE = 0x40;

    
Enables canonical equivalence.

When this flag is specified then two characters will be considered to match if, and only if, their full canonical decompositions match. The expression "a\u030A", for example, will match the string "\u00E5" when this flag is specified. By default, matching does not take canonical equivalence into account.

There is no embedded flag character for enabling canonical equivalence.

Specifying this flag may impose a performance penalty.

 
     public static final int CANON_EQ = 0x80;

    
Enables the Unicode version of Predefined character classes and POSIX character classes.

When this flag is specified then the (US-ASCII only) Predefined character classes and POSIX character classes are in conformance with Unicode Technical Standard #18: Unicode Regular Expression Annex C: Compatibility Properties.

The UNICODE_CHARACTER_CLASS mode can also be enabled via the embedded flag expression (?U).

The flag implies UNICODE_CASE, that is, it enables Unicode-aware case folding.

Specifying this flag may impose a performance penalty.

Since:
1.7
 
     public static final int UNICODE_CHARACTER_CLASS = 0x100;
 
     /* Pattern has only two serialized components: The pattern string
      * and the flags, which are all that is needed to recompile the pattern
      * when it is deserialized.
      */

    
use serialVersionUID from Merlin b59 for interoperability
 
     private static final long serialVersionUID = 5073258162644648461L;

    
The original regular-expression pattern string.

Serial:
 
     private String pattern;

    
The original pattern flags.

Serial:
 
     private int flags;

    
Boolean indicating this Pattern is compiled; this is necessary in order to lazily compile deserialized Patterns.
 
     private transient volatile boolean compiled = false;

    
The normalized pattern string.
 
     private transient String normalizedPattern;

    
The starting point of state machine for the find operation. This allows a match to start anywhere in the input.
 
     transient Node root;

    
The root of object tree for a match operation. The pattern is matched at the beginning. This may include a find that uses BnM or a First node.
 
     transient Node matchRoot;

    
Temporary storage used by parsing pattern slice.
 
     transient int[] buffer;

    
Map the "name" of the "named capturing group" to its group id node.
 
     transient volatile Map<StringIntegernamedGroups;

    
Temporary storage used while parsing group references.
 
     transient GroupHead[] groupNodes;

    
Temporary null terminated code point array used by pattern compiling.
 
     private transient int[] temp;

    
The number of capturing groups in this Pattern. Used by matchers to allocate storage needed to perform a match.
 
     transient int capturingGroupCount;

    
The local variable count used by parsing tree. Used by matchers to allocate storage needed to perform a match.
 
     transient int localCount;

    
Index into the pattern string that keeps track of how much has been parsed.
 
     private transient int cursor;

    
Holds the length of the pattern string.
    private transient int patternLength;

    
If the Start node might possibly match supplementary characters. It is set to true during compiling if (1) There is supplementary char in pattern, or (2) There is complement node of Category or Block
    private transient boolean hasSupplementary;

    
Compiles the given regular expression into a pattern.

Parameters:
regex The expression to be compiled
Throws:
PatternSyntaxException If the expression's syntax is invalid
    public static Pattern compile(String regex) {
        return new Pattern(regex, 0);
    }

    
Compiles the given regular expression into a pattern with the given flags.

Parameters:
regex The expression to be compiled
flags Match flags, a bit mask that may include CASE_INSENSITIVE, MULTILINE, DOTALL, UNICODE_CASE, CANON_EQ, UNIX_LINES, LITERAL, UNICODE_CHARACTER_CLASS and COMMENTS
Throws:
java.lang.IllegalArgumentException If bit values other than those corresponding to the defined match flags are set in flags
PatternSyntaxException If the expression's syntax is invalid
    public static Pattern compile(String regexint flags) {
        return new Pattern(regexflags);
    }

    
Returns the regular expression from which this pattern was compiled.

Returns:
The source of this pattern
    public String pattern() {
        return ;
    }

    

Returns the string representation of this pattern. This is the regular expression from which this pattern was compiled.

Returns:
The string representation of this pattern
Since:
1.5
    public String toString() {
        return ;
    }

    
Creates a matcher that will match the given input against this pattern.

Parameters:
input The character sequence to be matched
Returns:
A new matcher for this pattern
    public Matcher matcher(CharSequence input) {
        if (!) {
            synchronized(this) {
                if (!)
                    compile();
            }
        }
        Matcher m = new Matcher(thisinput);
        return m;
    }

    
Returns this pattern's match flags.

Returns:
The match flags specified when this pattern was compiled
    public int flags() {
        return ;
    }

    
Compiles the given regular expression and attempts to match the given input against it.

An invocation of this convenience method of the form

 Pattern.matches(regex, input);
behaves in exactly the same way as the expression
 Pattern.compile(regex).matcher(input).matches()

If a pattern is to be used multiple times, compiling it once and reusing it will be more efficient than invoking this method each time.

Parameters:
regex The expression to be compiled
input The character sequence to be matched
Throws:
PatternSyntaxException If the expression's syntax is invalid
    public static boolean matches(String regexCharSequence input) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(input);
        return m.matches();
    }

    
Splits the given input sequence around matches of this pattern.

The array returned by this method contains each substring of the input sequence that is terminated by another subsequence that matches this pattern or is terminated by the end of the input sequence. The substrings in the array are in the order in which they occur in the input. If this pattern does not match any subsequence of the input then the resulting array has just one element, namely the input sequence in string form.

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

The input "boo:and:foo", for example, yields the following results with these parameters:

Regex    

Limit    

Result    

:2{ "boo", "and:foo" }
:5{ "boo", "and", "foo" }
:-2{ "boo", "and", "foo" }
o5{ "b", "", ":and:f", "", "" }
o-2{ "b", "", ":and:f", "", "" }
o0{ "b", "", ":and:f" }

Parameters:
input The character sequence to be split
limit The result threshold, as described above
Returns:
The array of strings computed by splitting the input around matches of this pattern
    public String[] split(CharSequence inputint limit) {
        int index = 0;
        boolean matchLimited = limit > 0;
        ArrayList<StringmatchList = new ArrayList<>();
        Matcher m = matcher(input);
        // Add segments before each match found
        while(m.find()) {
            if (!matchLimited || matchList.size() < limit - 1) {
                String match = input.subSequence(indexm.start()).toString();
                matchList.add(match);
                index = m.end();
            } else if (matchList.size() == limit - 1) { // last one
                String match = input.subSequence(index,
                                                 input.length()).toString();
                matchList.add(match);
                index = m.end();
            }
        }
        // If no match was found, return this
        if (index == 0)
            return new String[] {input.toString()};
        // Add remaining segment
        if (!matchLimited || matchList.size() < limit)
            matchList.add(input.subSequence(indexinput.length()).toString());
        // Construct result
        int resultSize = matchList.size();
        if (limit == 0)
            while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
                resultSize--;
        String[] result = new String[resultSize];
        return matchList.subList(0, resultSize).toArray(result);
    }

    
Splits the given input sequence around matches of this pattern.

This method works as if by invoking the two-argument split(java.lang.CharSequence,int) method with the given input sequence and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The input "boo:and:foo", for example, yields the following results with these expressions:

Regex    

Result

:{ "boo", "and", "foo" }
o{ "b", "", ":and:f" }

Parameters:
input The character sequence to be split
Returns:
The array of strings computed by splitting the input around matches of this pattern
    public String[] split(CharSequence input) {
        return split(input, 0);
    }

    
Returns a literal pattern String for the specified String.

This method produces a String that can be used to create a Pattern that would match the string s as if it were a literal pattern.

Metacharacters or escape sequences in the input sequence will be given no special meaning.

Parameters:
s The string to be literalized
Returns:
A literal string replacement
Since:
1.5
    public static String quote(String s) {
        int slashEIndex = s.indexOf("\\E");
        if (slashEIndex == -1)
            return "\\Q" + s + "\\E";
        StringBuilder sb = new StringBuilder(s.length() * 2);
        sb.append("\\Q");
        slashEIndex = 0;
        int current = 0;
        while ((slashEIndex = s.indexOf("\\E"current)) != -1) {
            sb.append(s.substring(currentslashEIndex));
            current = slashEIndex + 2;
            sb.append("\\E\\\\E\\Q");
        }
        sb.append(s.substring(currents.length()));
        sb.append("\\E");
        return sb.toString();
    }

    
Recompile the Pattern instance from a stream. The original pattern string is read in and the object tree is recompiled from it.
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOExceptionClassNotFoundException {
        // Read in all fields
        s.defaultReadObject();
        // Initialize counts
         = 1;
         = 0;
        // if length > 0, the Pattern is lazily compiled
         = false;
        if (.length() == 0) {
             = new Start();
             = ;
             = true;
        }
    }

    
This private constructor is used to create all Patterns. The pattern string and match flags are all that is needed to completely describe a Pattern. An empty pattern string results in an object tree with only a Start node and a LastNode node.
    private Pattern(String pint f) {
         = p;
         = f;
        // to use UNICODE_CASE if UNICODE_CHARACTER_CLASS present
        if (( & ) != 0)
             |= ;
        // Reset group index count
         = 1;
         = 0;
        if (.length() > 0) {
            compile();
        } else {
             = new Start();
             = ;
        }
    }

    
The pattern is converted to normalizedD form and then a pure group is constructed to match canonical equivalences of the characters.
    private void normalize() {
        boolean inCharClass = false;
        int lastCodePoint = -1;
        // Convert pattern into normalizedD form
         = Normalizer.normalize(..);
        // Modify pattern to match canonical equivalences
        StringBuilder newPattern = new StringBuilder();
        for(int i=0; i<; ) {
            int c = .codePointAt(i);
            StringBuilder sequenceBuffer;
            if ((Character.getType(c) == .)
                && (lastCodePoint != -1)) {
                sequenceBuffer = new StringBuilder();
                sequenceBuffer.appendCodePoint(lastCodePoint);
                sequenceBuffer.appendCodePoint(c);
                while(Character.getType(c) == .) {
                    i += Character.charCount(c);
                    if (i >= )
                        break;
                    c = .codePointAt(i);
                    sequenceBuffer.appendCodePoint(c);
                }
                String ea = produceEquivalentAlternation(
                                               sequenceBuffer.toString());
                newPattern.setLength(newPattern.length()-Character.charCount(lastCodePoint));
                newPattern.append("(?:").append(ea).append(")");
            } else if (c == '[' && lastCodePoint != '\\') {
                i = normalizeCharClass(newPatterni);
            } else {
                newPattern.appendCodePoint(c);
            }
            lastCodePoint = c;
            i += Character.charCount(c);
        }
         = newPattern.toString();
    }

    
Complete the character class being parsed and add a set of alternations to it that will match the canonical equivalences of the characters within the class.
    private int normalizeCharClass(StringBuilder newPatternint i) {
        StringBuilder charClass = new StringBuilder();
        StringBuilder eq = null;
        int lastCodePoint = -1;
        String result;
        i++;
        charClass.append("[");
        while(true) {
            int c = .codePointAt(i);
            StringBuilder sequenceBuffer;
            if (c == ']' && lastCodePoint != '\\') {
                charClass.append((char)c);
                break;
            } else if (Character.getType(c) == .) {
                sequenceBuffer = new StringBuilder();
                sequenceBuffer.appendCodePoint(lastCodePoint);
                while(Character.getType(c) == .) {
                    sequenceBuffer.appendCodePoint(c);
                    i += Character.charCount(c);
                    if (i >= .length())
                        break;
                    c = .codePointAt(i);
                }
                String ea = produceEquivalentAlternation(
                                                  sequenceBuffer.toString());
                charClass.setLength(charClass.length()-Character.charCount(lastCodePoint));
                if (eq == null)
                    eq = new StringBuilder();
                eq.append('|');
                eq.append(ea);
            } else {
                charClass.appendCodePoint(c);
                i++;
            }
            if (i == .length())
                throw error("Unclosed character class");
            lastCodePoint = c;
        }
        if (eq != null) {
            result = "(?:"+charClass.toString()+eq.toString()+")";
        } else {
            result = charClass.toString();
        }
        newPattern.append(result);
        return i;
    }

    
Given a specific sequence composed of a regular character and combining marks that follow it, produce the alternation that will match all canonical equivalences of that sequence.
    private String produceEquivalentAlternation(String source) {
        int len = countChars(source, 0, 1);
        if (source.length() == len)
            // source has one character.
            return source;
        String base = source.substring(0,len);
        String combiningMarks = source.substring(len);
        String[] perms = producePermutations(combiningMarks);
        StringBuilder result = new StringBuilder(source);
        // Add combined permutations
        for(int x=0; x<perms.lengthx++) {
            String next = base + perms[x];
            if (x>0)
                result.append("|"+next);
            next = composeOneStep(next);
            if (next != null)
                result.append("|"+produceEquivalentAlternation(next));
        }
        return result.toString();
    }

    
Returns an array of strings that have all the possible permutations of the characters in the input string. This is used to get a list of all possible orderings of a set of combining marks. Note that some of the permutations are invalid because of combining class collisions, and these possibilities must be removed because they are not canonically equivalent.
    private String[] producePermutations(String input) {
        if (input.length() == countChars(input, 0, 1))
            return new String[] {input};
        if (input.length() == countChars(input, 0, 2)) {
            int c0 = Character.codePointAt(input, 0);
            int c1 = Character.codePointAt(input, Character.charCount(c0));
            if (getClass(c1) == getClass(c0)) {
                return new String[] {input};
            }
            String[] result = new String[2];
            result[0] = input;
            StringBuilder sb = new StringBuilder(2);
            sb.appendCodePoint(c1);
            sb.appendCodePoint(c0);
            result[1] = sb.toString();
            return result;
        }
        int length = 1;
        int nCodePoints = countCodePoints(input);
        for(int x=1; x<nCodePointsx++)
            length = length * (x+1);
        String[] temp = new String[length];
        int combClass[] = new int[nCodePoints];
        for(int x=0, i=0; x<nCodePointsx++) {
            int c = Character.codePointAt(inputi);
            combClass[x] = getClass(c);
            i +=  Character.charCount(c);
        }
        // For each char, take it out and add the permutations
        // of the remaining chars
        int index = 0;
        int len;
        // offset maintains the index in code units.
loop:   for(int x=0, offset=0; x<nCodePointsx++, offset+=len) {
            len = countChars(inputoffset, 1);
            boolean skip = false;
            for(int y=x-1; y>=0; y--) {
                if (combClass[y] == combClass[x]) {
                    continue loop;
                }
            }
            StringBuilder sb = new StringBuilder(input);
            String otherChars = sb.delete(offsetoffset+len).toString();
            String[] subResult = producePermutations(otherChars);
            String prefix = input.substring(offsetoffset+len);
            for(int y=0; y<subResult.lengthy++)
                temp[index++] =  prefix + subResult[y];
        }
        String[] result = new String[index];
        for (int x=0; x<indexx++)
            result[x] = temp[x];
        return result;
    }
    private int getClass(int c) {
        return sun.text.Normalizer.getCombiningClass(c);
    }

    
Attempts to compose input by combining the first character with the first combining mark following it. Returns a String that is the composition of the leading character with its first combining mark followed by the remaining combining marks. Returns null if the first two characters cannot be further composed.
    private String composeOneStep(String input) {
        int len = countChars(input, 0, 2);
        String firstTwoCharacters = input.substring(0, len);
        String result = Normalizer.normalize(firstTwoCharacters..);
        if (result.equals(firstTwoCharacters))
            return null;
        else {
            String remainder = input.substring(len);
            return result + remainder;
        }
    }

    
Preprocess any \Q...\E sequences in `temp', meta-quoting them. See the description of `quotemeta' in perlfunc(1).
    private void RemoveQEQuoting() {
        final int pLen = ;
        int i = 0;
        while (i < pLen-1) {
            if ([i] != '\\')
                i += 1;
            else if ([i + 1] != 'Q')
                i += 2;
            else
                break;
        }
        if (i >= pLen - 1)    // No \Q sequence found
            return;
        int j = i;
        i += 2;
        int[] newtemp = new int[j + 2*(pLen-i) + 2];
        System.arraycopy(, 0, newtemp, 0, j);
        boolean inQuote = true;
        while (i < pLen) {
            int c = [i++];
            if (! ASCII.isAscii(c) || ASCII.isAlnum(c)) {
                newtemp[j++] = c;
            } else if (c != '\\') {
                if (inQuotenewtemp[j++] = '\\';
                newtemp[j++] = c;
            } else if (inQuote) {
                if ([i] == 'E') {
                    i++;
                    inQuote = false;
                } else {
                    newtemp[j++] = '\\';
                    newtemp[j++] = '\\';
                }
            } else {
                if ([i] == 'Q') {
                    i++;
                    inQuote = true;
                } else {
                    newtemp[j++] = c;
                    if (i != pLen)
                        newtemp[j++] = [i++];
                }
            }
        }
         = j;
         = Arrays.copyOf(newtempj + 2); // double zero termination
    }

    
Copies regular expression to an int array and invokes the parsing of the expression which will create the object tree.
    private void compile() {
        // Handle canonical equivalences
        if (has() && !has()) {
            normalize();
        } else {
             = ;
        }
        // Copy pattern to int array for convenience
        // Use double zero to terminate pattern
         = new int[ + 2];
         = false;
        int ccount = 0;
        // Convert all chars into code points
        for (int x = 0; x < x += Character.charCount(c)) {
            c = .codePointAt(x);
            if (isSupplementary(c)) {
                 = true;
            }
            [count++] = c;
        }
         = count;   // patternLength now in code points
        if (! has())
            RemoveQEQuoting();
        // Allocate all temporary objects here.
         = new int[32];
         = new GroupHead[10];
         = null;
        if (has()) {
            // Literal pattern handling
             = newSlice();
            . = ;
        } else {
            // Start recursive descent parsing
             = expr();
            // Check extra pattern characters
            if ( != ) {
                if (peek() == ')') {
                    throw error("Unmatched closing ')'");
                } else {
                    throw error("Unexpected internal error");
                }
            }
        }
        // Peephole optimization
        if ( instanceof Slice) {
             = BnM.optimize();
            if ( == ) {
                 =  ? new StartS() : new Start();
            }
        } else if ( instanceof Begin ||  instanceof First) {
             = ;
        } else {
             =  ? new StartS() : new Start();
        }
        // Release temporary storage
         = null;
         = null;
         = null;
         = 0;
         = true;
    }
        if ( == null)
             = new HashMap<>(2);
        return ;
    }

    
Used to print out a subtree of the Pattern to help with debugging.
    private static void printObjectTree(Node node) {
        while(node != null) {
            if (node instanceof Prolog) {
                ..println(node);
                printObjectTree(((Prolog)node).);
                ..println("**** end contents prolog loop");
            } else if (node instanceof Loop) {
                ..println(node);
                printObjectTree(((Loop)node).);
                ..println("**** end contents Loop body");
            } else if (node instanceof Curly) {
                ..println(node);
                printObjectTree(((Curly)node).);
                ..println("**** end contents Curly body");
            } else if (node instanceof GroupCurly) {
                ..println(node);
                printObjectTree(((GroupCurly)node).);
                ..println("**** end contents GroupCurly body");
            } else if (node instanceof GroupTail) {
                ..println(node);
                ..println("Tail next is "+node.next);
                return;
            } else {
                ..println(node);
            }
            node = node.next;
            if (node != null)
                ..println("->next:");
            if (node == .) {
                ..println("Accept Node");
                node = null;
            }
       }
    }

    
Used to accumulate information about a subtree of the object graph so that optimizations can be applied to the subtree.
    static final class TreeInfo {
        int minLength;
        int maxLength;
        boolean maxValid;
        boolean deterministic;
        TreeInfo() {
            reset();
        }
        void reset() {
             = 0;
             = 0;
             = true;
             = true;
        }
    }
    /*
     * The following private methods are mainly used to improve the
     * readability of the code. In order to let the Java compiler easily
     * inline them, we should not put many assertions or error checks in them.
     */

    
Indicates whether a particular flag is set or not.
    private boolean has(int f) {
        return ( & f) != 0;
    }

    
Match next character, signal error if failed.
    private void accept(int chString s) {
        int testChar = [++];
        if (has())
            testChar = parsePastWhitespace(testChar);
        if (ch != testChar) {
            throw error(s);
        }
    }

    
Mark the end of pattern with a specific character.
    private void mark(int c) {
        [] = c;
    }

    
Peek the next character, and do not advance the cursor.
    private int peek() {
        int ch = [];
        if (has())
            ch = peekPastWhitespace(ch);
        return ch;
    }

    
Read the next character, and advance the cursor by one.
    private int read() {
        int ch = [++];
        if (has())
            ch = parsePastWhitespace(ch);
        return ch;
    }

    
Read the next character, and advance the cursor by one, ignoring the COMMENTS setting
    private int readEscaped() {
        int ch = [++];
        return ch;
    }

    
Advance the cursor by one, and peek the next character.
    private int next() {
        int ch = [++];
        if (has())
            ch = peekPastWhitespace(ch);
        return ch;
    }

    
Advance the cursor by one, and peek the next character, ignoring the COMMENTS setting
    private int nextEscaped() {
        int ch = [++];
        return ch;
    }

    
If in xmode peek past whitespace and comments.
    private int peekPastWhitespace(int ch) {
        while (ASCII.isSpace(ch) || ch == '#') {
            while (ASCII.isSpace(ch))
                ch = [++];
            if (ch == '#') {
                ch = peekPastLine();
            }
        }
        return ch;
    }

    
If in xmode parse past whitespace and comments.
    private int parsePastWhitespace(int ch) {
        while (ASCII.isSpace(ch) || ch == '#') {
            while (ASCII.isSpace(ch))
                ch = [++];
            if (ch == '#')
                ch = parsePastLine();
        }
        return ch;
    }

    
xmode parse past comment to end of line.
    private int parsePastLine() {
        int ch = [++];
        while (ch != 0 && !isLineSeparator(ch))
            ch = [++];
        return ch;
    }

    
xmode peek past comment to end of line.
    private int peekPastLine() {
        int ch = [++];
        while (ch != 0 && !isLineSeparator(ch))
            ch = [++];
        return ch;
    }

    
Determines if character is a line separator in the current mode
    private boolean isLineSeparator(int ch) {
        if (has()) {
            return ch == '\n';
        } else {
            return (ch == '\n' ||
                    ch == '\r' ||
                    (ch|1) == '\u2029' ||
                    ch == '\u0085');
        }
    }

    
Read the character after the next one, and advance the cursor by two.
    private int skip() {
        int i = ;
        int ch = [i+1];
         = i + 2;
        return ch;
    }

    
Unread one next character, and retreat cursor by one.
    private void unread() {
        --;
    }

    
Internal method used for handling all syntax errors. The pattern is displayed with a pointer to aid in locating the syntax error.
    private PatternSyntaxException error(String s) {
        return new PatternSyntaxException(s,   - 1);
    }

    
Determines if there is any supplementary character or unpaired surrogate in the specified range.
    private boolean findSupplementary(int startint end) {
        for (int i = starti < endi++) {
            if (isSupplementary([i]))
                return true;
        }
        return false;
    }

    
Determines if the specified code point is a supplementary character or unpaired surrogate.
    private static final boolean isSupplementary(int ch) {
        return ch >= . ||
               Character.isSurrogate((char)ch);
    }

    
The following methods handle the main parsing. They are sorted according to their precedence order, the lowest one first.


    
The expression is parsed with branch nodes added for alternations. This may be called recursively to parse sub expressions that may contain alternations.
    private Node expr(Node end) {
        Node prev = null;
        Node firstTail = null;
        Node branchConn = null;
        for (;;) {
            Node node = sequence(end);
            Node nodeTail = ;      //double return
            if (prev == null) {
                prev = node;
                firstTail = nodeTail;
            } else {
                // Branch
                if (branchConn == null) {
                    branchConn = new BranchConn();
                    branchConn.next = end;
                }
                if (node == end) {
                    // if the node returned from sequence() is "end"
                    // we have an empty expr, set a null atom into
                    // the branch to indicate to go "next" directly.
                    node = null;
                } else {
                    // the "tail.next" of each atom goes to branchConn
                    nodeTail.next = branchConn;
                }
                if (prev instanceof Branch) {
                    ((Branch)prev).add(node);
                } else {
                    if (prev == end) {
                        prev = null;
                    } else {
                        // replace the "end" with "branchConn" at its tail.next
                        // when put the "prev" into the branch as the first atom.
                        firstTail.next = branchConn;
                    }
                    prev = new Branch(prevnodebranchConn);
                }
            }
            if (peek() != '|') {
                return prev;
            }
            next();
        }
    }

    
Parsing of sequences between alternations.
    private Node sequence(Node end) {
        Node head = null;
        Node tail = null;
        Node node = null;
    LOOP:
        for (;;) {
            int ch = peek();
            switch (ch) {
            case '(':
                // Because group handles its own closure,
                // we need to treat it differently
                node = group0();
                // Check for comment or flag group
                if (node == null)
                    continue;
                if (head == null)
                    head = node;
                else
                    tail.next = node;
                // Double return: Tail was returned in root
                tail = ;
                continue;
            case '[':
                node = clazz(true);
                break;
            case '\\':
                ch = nextEscaped();
                if (ch == 'p' || ch == 'P') {
                    boolean oneLetter = true;
                    boolean comp = (ch == 'P');
                    ch = next(); // Consume { if present
                    if (ch != '{') {
                        unread();
                    } else {
                        oneLetter = false;
                    }
                    node = family(oneLettercomp);
                } else {
                    unread();
                    node = atom();
                }
                break;
            case '^':
                next();
                if (has()) {
                    if (has())
                        node = new UnixCaret();
                    else
                        node = new Caret();
                } else {
                    node = new Begin();
                }
                break;
            case '$':
                next();
                if (has())
                    node = new UnixDollar(has());
                else
                    node = new Dollar(has());
                break;
            case '.':
                next();
                if (has()) {
                    node = new All();
                } else {
                    if (has())
                        node = new UnixDot();
                    else {
                        node = new Dot();
                    }
                }
                break;
            case '|':
            case ')':
                break LOOP;
            case ']'// Now interpreting dangling ] and } as literals
            case '}':
                node = atom();
                break;
            case '?':
            case '*':
            case '+':
                next();
                throw error("Dangling meta character '" + ((char)ch) + "'");
            case 0:
                if ( >= ) {
                    break LOOP;
                }
                // Fall through
            default:
                node = atom();
                break;
            }
            node = closure(node);
            if (head == null) {
                head = tail = node;
            } else {
                tail.next = node;
                tail = node;
            }
        }
        if (head == null) {
            return end;
        }
        tail.next = end;
         = tail;      //double return
        return head;
    }

    
Parse and add a new Single or Slice.
    private Node atom() {
        int first = 0;
        int prev = -1;
        boolean hasSupplementary = false;
        int ch = peek();
        for (;;) {
            switch (ch) {
            case '*':
            case '+':
            case '?':
            case '{':
                if (first > 1) {
                     = prev;    // Unwind one character
                    first--;
                }
                break;
            case '$':
            case '.':
            case '^':
            case '(':
            case '[':
            case '|':
            case ')':
                break;
            case '\\':
                ch = nextEscaped();
                if (ch == 'p' || ch == 'P') { // Property
                    if (first > 0) { // Slice is waiting; handle it first
                        unread();
                        break;
                    } else { // No slice; just return the family node
                        boolean comp = (ch == 'P');
                        boolean oneLetter = true;
                        ch = next(); // Consume { if present
                        if (ch != '{')
                            unread();
                        else
                            oneLetter = false;
                        return family(oneLettercomp);
                    }
                }
                unread();
                prev = ;
                ch = escape(falsefirst == 0);
                if (ch >= 0) {
                    append(chfirst);
                    first++;
                    if (isSupplementary(ch)) {
                        hasSupplementary = true;
                    }
                    ch = peek();
                    continue;
                } else if (first == 0) {
                    return ;
                }
                // Unwind meta escape sequence
                 = prev;
                break;
            case 0:
                if ( >= ) {
                    break;
                }
                // Fall through
            default:
                prev = ;
                append(chfirst);
                first++;
                if (isSupplementary(ch)) {
                    hasSupplementary = true;
                }
                ch = next();
                continue;
            }
            break;
        }
        if (first == 1) {
            return newSingle([0]);
        } else {
            return newSlice(firsthasSupplementary);
        }
    }
    private void append(int chint len) {
        if (len >= .) {
            int[] tmp = new int[len+len];
            System.arraycopy(, 0, tmp, 0, len);
             = tmp;
        }
        [len] = ch;
    }

    
Parses a backref greedily, taking as many numbers as it can. The first digit is always treated as a backref, but multi digit numbers are only treated as a backref if at least that many backrefs exist at this point in the regex.
    private Node ref(int refNum) {
        boolean done = false;
        while(!done) {
            int ch = peek();
            switch(ch) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                int newRefNum = (refNum * 10) + (ch - '0');
                // Add another number if it doesn't make a group
                // that doesn't exist
                if ( - 1 < newRefNum) {
                    done = true;
                    break;
                }
                refNum = newRefNum;
                read();
                break;
            default:
                done = true;
                break;
            }
        }
        if (has())
            return new CIBackRef(refNumhas());
        else
            return new BackRef(refNum);
    }

    
Parses an escape sequence to determine the actual value that needs to be matched. If -1 is returned and create was true a new object was added to the tree to handle the escape sequence. If the returned value is greater than zero, it is the value that matches the escape sequence.
    private int escape(boolean inclassboolean create) {
        int ch = skip();
        switch (ch) {
        case '0':
            return o();
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            if (inclassbreak;
            if (create) {
                 = ref((ch - '0'));
            }
            return -1;
        case 'A':
            if (inclassbreak;
            if (create = new Begin();
            return -1;
        case 'B':
            if (inclassbreak;
            if (create = new Bound(.has());
            return -1;
        case 'C':
            break;
        case 'D':
            if (create = has()
                               ? new Utype(.).complement()
                               : new Ctype(.).complement();
            return -1;
        case 'E':
        case 'F':
            break;
        case 'G':
            if (inclassbreak;
            if (create = new LastMatch();
            return -1;
        case 'H':
        case 'I':
        case 'J':
        case 'K':
        case 'L':
        case 'M':
        case 'N':
        case 'O':
        case 'P':
        case 'Q':
        case 'R':
            break;
        case 'S':
            if (create = has()
                               ? new Utype(.).complement()
                               : new Ctype(.).complement();
            return -1;
        case 'T':
        case 'U':
        case 'V':
            break;
        case 'W':
            if (create = has()
                               ? new Utype(.).complement()
                               : new Ctype(.).complement();
            return -1;
        case 'X':
        case 'Y':
            break;
        case 'Z':
            if (inclassbreak;
            if (create) {
                if (has())
                     = new UnixDollar(false);
                else
                     = new Dollar(false);
            }
            return -1;
        case 'a':
            return '\007';
        case 'b':
            if (inclassbreak;
            if (create = new Bound(.has());
            return -1;
        case 'c':
            return c();
        case 'd':
            if (create = has()
                               ? new Utype(.)
                               : new Ctype(.);
            return -1;
        case 'e':
            return '\033';
        case 'f':
            return '\f';
        case 'g':
        case 'h':
        case 'i':
        case 'j':
            break;
        case 'k':
            if (inclass)
                break;
            if (read() != '<')
                throw error("\\k is not followed by '<' for named capturing group");
            String name = groupname(read());
            if (!namedGroups().containsKey(name))
                throw error("(named capturing group <"name+"> does not exit");
            if (create) {
                if (has())
                     = new CIBackRef(namedGroups().get(name), has());
                else
                     = new BackRef(namedGroups().get(name));
            }
            return -1;
        case 'l':
        case 'm':
            break;
        case 'n':
            return '\n';
        case 'o':
        case 'p':
        case 'q':
            break;
        case 'r':
            return '\r';
        case 's':
            if (create = has()
                               ? new Utype(.)
                               : new Ctype(.);
            return -1;
        case 't':
            return '\t';
        case 'u':
            return u();
        case 'v':
            return '\013';
        case 'w':
            if (create = has()
                               ? new Utype(.)
                               : new Ctype(.);
            return -1;
        case 'x':
            return x();
        case 'y':
            break;
        case 'z':
            if (inclassbreak;
            if (create = new End();
            return -1;
        default:
            return ch;
        }
        throw error("Illegal/unsupported escape sequence");
    }

    
Parse a character class, and return the node that matches it. Consumes a ] on the way out if consume is true. Usually consume is true except for the case of [abc&&def] where def is a separate right hand node with "understood" brackets.
    private CharProperty clazz(boolean consume) {
        CharProperty prev = null;
        CharProperty node = null;
        BitClass bits = new BitClass();
        boolean include = true;
        boolean firstInClass = true;
        int ch = next();
        for (;;) {
            switch (ch) {
                case '^':
                    // Negates if first char in a class, otherwise literal
                    if (firstInClass) {
                        if ([-1] != '[')
                            break;
                        ch = next();
                        include = !include;
                        continue;
                    } else {
                        // ^ not first in class, treat as literal
                        break;
                    }
                case '[':
                    firstInClass = false;
                    node = clazz(true);
                    if (prev == null)
                        prev = node;
                    else
                        prev = union(prevnode);
                    ch = peek();
                    continue;
                case '&':
                    firstInClass = false;
                    ch = next();
                    if (ch == '&') {
                        ch = next();
                        CharProperty rightNode = null;
                        while (ch != ']' && ch != '&') {
                            if (ch == '[') {
                                if (rightNode == null)
                                    rightNode = clazz(true);
                                else
                                    rightNode = union(rightNodeclazz(true));
                            } else { // abc&&def
                                unread();
                                rightNode = clazz(false);
                            }
                            ch = peek();
                        }
                        if (rightNode != null)
                            node = rightNode;
                        if (prev == null) {
                            if (rightNode == null)
                                throw error("Bad class syntax");
                            else
                                prev = rightNode;
                        } else {
                            prev = intersection(prevnode);
                        }
                    } else {
                        // treat as a literal &
                        unread();
                        break;
                    }
                    continue;
                case 0:
                    firstInClass = false;
                    if ( >= )
                        throw error("Unclosed character class");
                    break;
                case ']':
                    firstInClass = false;
                    if (prev != null) {
                        if (consume)
                            next();
                        return prev;
                    }
                    break;
                default:
                    firstInClass = false;
                    break;
            }
            node = range(bits);
            if (include) {
                if (prev == null) {
                    prev = node;
                } else {
                    if (prev != node)
                        prev = union(prevnode);
                }
            } else {
                if (prev == null) {
                    prev = node.complement();
                } else {
                    if (prev != node)
                        prev = setDifference(prevnode);
                }
            }
            ch = peek();
        }
    }
    private CharProperty bitsOrSingle(BitClass bitsint ch) {
        /* Bits can only handle codepoints in [u+0000-u+00ff] range.
           Use "single" node instead of bits when dealing with unicode
           case folding for codepoints listed below.
           (1)Uppercase out of range: u+00ff, u+00b5
              toUpperCase(u+00ff) -> u+0178
              toUpperCase(u+00b5) -> u+039c
           (2)LatinSmallLetterLongS u+17f
              toUpperCase(u+017f) -> u+0053
           (3)LatinSmallLetterDotlessI u+131
              toUpperCase(u+0131) -> u+0049
           (4)LatinCapitalLetterIWithDotAbove u+0130
              toLowerCase(u+0130) -> u+0069
           (5)KelvinSign u+212a
              toLowerCase(u+212a) ==> u+006B
           (6)AngstromSign u+212b
              toLowerCase(u+212b) ==> u+00e5
        */
        int d;
        if (ch < 256 &&
            !(has() && has() &&
              (ch == 0xff || ch == 0xb5 ||
               ch == 0x49 || ch == 0x69 ||  //I and i
               ch == 0x53 || ch == 0x73 ||  //S and s
               ch == 0x4b || ch == 0x6b ||  //K and k
               ch == 0xc5 || ch == 0xe5)))  //A+ring
            return bits.add(chflags());
        return newSingle(ch);
    }

    
Parse a single character or a character range in a character class and return its representative node.
    private CharProperty range(BitClass bits) {
        int ch = peek();
        if (ch == '\\') {
            ch = nextEscaped();
            if (ch == 'p' || ch == 'P') { // A property
                boolean comp = (ch == 'P');
                boolean oneLetter = true;
                // Consume { if present
                ch = next();
                if (ch != '{')
                    unread();
                else
                    oneLetter = false;
                return family(oneLettercomp);
            } else { // ordinary escape
                unread();
                ch = escape(truetrue);
                if (ch == -1)
                    return (CharProperty;
            }
        } else {
            ch = single();
        }
        if (ch >= 0) {
            if (peek() == '-') {
                int endRange = [+1];
                if (endRange == '[') {
                    return bitsOrSingle(bitsch);
                }
                if (endRange != ']') {
                    next();
                    int m = single();
                    if (m < ch)
                        throw error("Illegal character range");
                    if (has())
                        return caseInsensitiveRangeFor(chm);
                    else
                        return rangeFor(chm);
                }
            }
            return bitsOrSingle(bitsch);
        }
        throw error("Unexpected character '"+((char)ch)+"'");
    }
    private int single() {
        int ch = peek();
        switch (ch) {
        case '\\':
            return escape(truefalse);
        default:
            next();
            return ch;
        }
    }

    
Parses a Unicode character family and returns its representative node.
    private CharProperty family(boolean singleLetter,
                                boolean maybeComplement)
    {
        next();
        String name;
        CharProperty node = null;
        if (singleLetter) {
            int c = [];
            if (!Character.isSupplementaryCodePoint(c)) {
                name = String.valueOf((char)c);
            } else {
                name = new String(, 1);
            }
            read();
        } else {
            int i = ;
            mark('}');
            while(read() != '}') {
            }
            mark('\000');
            int j = ;
            if (j > )
                throw error("Unclosed character family");
            if (i + 1 >= j)
                throw error("Empty character family");
            name = new String(ij-i-1);
        }
        int i = name.indexOf('=');
        if (i != -1) {
            // property construct \p{name=value}
            String value = name.substring(i + 1);
            name = name.substring(0, i).toLowerCase(.);
            if ("sc".equals(name) || "script".equals(name)) {
                node = unicodeScriptPropertyFor(value);
            } else if ("blk".equals(name) || "block".equals(name)) {
                node = unicodeBlockPropertyFor(value);
            } else if ("gc".equals(name) || "general_category".equals(name)) {
                node = charPropertyNodeFor(value);
            } else {
                throw error("Unknown Unicode property {name=<" + name + ">, "
                             + "value=<" + value + ">}");
            }
        } else {
            if (name.startsWith("In")) {
                // \p{inBlockName}
                node = unicodeBlockPropertyFor(name.substring(2));
            } else if (name.startsWith("Is")) {
                // \p{isGeneralCategory} and \p{isScriptName}
                name = name.substring(2);
                UnicodeProp uprop = UnicodeProp.forName(name);
                if (uprop != null)
                    node = new Utype(uprop);
                if (node == null)
                    node = CharPropertyNames.charPropertyFor(name);
                if (node == null)
                    node = unicodeScriptPropertyFor(name);
            } else {
                if (has()) {
                    UnicodeProp uprop = UnicodeProp.forPOSIXName(name);
                    if (uprop != null)
                        node = new Utype(uprop);
                }
                if (node == null)
                    node = charPropertyNodeFor(name);
            }
        }
        if (maybeComplement) {
            if (node instanceof Category || node instanceof Block)
                 = true;
            node = node.complement();
        }
        return node;
    }


    
Returns a CharProperty matching all characters belong to a UnicodeScript.
        final Character.UnicodeScript script;
        try {
            script = Character.UnicodeScript.forName(name);
        } catch (IllegalArgumentException iae) {
            throw error("Unknown character script name {" + name + "}");
        }
        return new Script(script);
    }

    
Returns a CharProperty matching all characters in a UnicodeBlock.
    private CharProperty unicodeBlockPropertyFor(String name) {
        final Character.UnicodeBlock block;
        try {
            block = Character.UnicodeBlock.forName(name);
        } catch (IllegalArgumentException iae) {
            throw error("Unknown character block name {" + name + "}");
        }
        return new Block(block);
    }

    
Returns a CharProperty matching all characters in a named property.
    private CharProperty charPropertyNodeFor(String name) {
        CharProperty p = CharPropertyNames.charPropertyFor(name);
        if (p == null)
            throw error("Unknown character property name {" + name + "}");
        return p;
    }

    
Parses and returns the name of a "named capturing group", the trailing ">" is consumed after parsing.
    private String groupname(int ch) {
        StringBuilder sb = new StringBuilder();
        sb.append(Character.toChars(ch));
        while (ASCII.isLower(ch=read()) || ASCII.isUpper(ch) ||
               ASCII.isDigit(ch)) {
            sb.append(Character.toChars(ch));
        }
        if (sb.length() == 0)
            throw error("named capturing group has 0 length name");
        if (ch != '>')
            throw error("named capturing group is missing trailing '>'");
        return sb.toString();
    }

    
Parses a group and returns the head node of a set of nodes that process the group. Sometimes a double return system is used where the tail is returned in root.
    private Node group0() {
        boolean capturingGroup = false;
        Node head = null;
        Node tail = null;
        int save = ;
         = null;
        int ch = next();
        if (ch == '?') {
            ch = skip();
            switch (ch) {
            case ':':   //  (?:xxx) pure group
                head = createGroup(true);
                tail = ;
                head.next = expr(tail);
                break;
            case '=':   // (?=xxx) and (?!xxx) lookahead
            case '!':
                head = createGroup(true);
                tail = ;
                head.next = expr(tail);
                if (ch == '=') {
                    head = tail = new Pos(head);
                } else {
                    head = tail = new Neg(head);
                }
                break;
            case '>':   // (?>xxx)  independent group
                head = createGroup(true);
                tail = ;
                head.next = expr(tail);
                head = tail = new Ques(head);
                break;
            case '<':   // (?<xxx)  look behind
                ch = read();
                if (ASCII.isLower(ch) || ASCII.isUpper(ch)) {
                    // named captured group
                    String name = groupname(ch);
                    if (namedGroups().containsKey(name))
                        throw error("Named capturing group <" + name
                                    + "> is already defined");
                    capturingGroup = true;
                    head = createGroup(false);
                    tail = ;
                    namedGroups().put(name-1);
                    head.next = expr(tail);
                    break;
                }
                int start = ;
                head = createGroup(true);
                tail = ;
                head.next = expr(tail);
                tail.next = ;
                TreeInfo info = new TreeInfo();
                head.study(info);
                if (info.maxValid == false) {
                    throw error("Look-behind group does not have "
                                + "an obvious maximum length");
                }
                boolean hasSupplementary = findSupplementary(start);
                if (ch == '=') {
                    head = tail = (hasSupplementary ?
                                   new BehindS(headinfo.maxLength,
                                               info.minLength) :
                                   new Behind(headinfo.maxLength,
                                              info.minLength));
                } else if (ch == '!') {
                    head = tail = (hasSupplementary ?
                                   new NotBehindS(headinfo.maxLength,
                                                  info.minLength) :
                                   new NotBehind(headinfo.maxLength,
                                                 info.minLength));
                } else {
                    throw error("Unknown look-behind group");
                }
                break;
            case '$':
            case '@':
                throw error("Unknown group type");
            default:    // (?xxx:) inlined match flags
                unread();
                addFlag();
                ch = read();
                if (ch == ')') {
                    return null;    // Inline modifier only
                }
                if (ch != ':') {
                    throw error("Unknown inline modifier");
                }
                head = createGroup(true);
                tail = ;
                head.next = expr(tail);
                break;
            }
        } else { // (xxx) a regular group
            capturingGroup = true;
            head = createGroup(false);
            tail = ;
            head.next = expr(tail);
        }
        accept(')'"Unclosed group");
         = save;
        // Check for quantifiers
        Node node = closure(head);
        if (node == head) { // No closure
             = tail;
            return node;    // Dual return
        }
        if (head == tail) { // Zero length assertion
             = node;
            return node;    // Dual return
        }
        if (node instanceof Ques) {
            Ques ques = (Quesnode;
            if (ques.type == ) {
                 = node;
                return node;
            }
            tail.next = new BranchConn();
            tail = tail.next;
            if (ques.type == ) {
                head = new Branch(headnulltail);
            } else { // Reluctant quantifier
                head = new Branch(nullheadtail);
            }
             = tail;
            return head;
        } else if (node instanceof Curly) {
            Curly curly = (Curlynode;
            if (curly.type == ) {
                 = node;
                return node;
            }
            // Discover if the group is deterministic
            TreeInfo info = new TreeInfo();
            if (head.study(info)) { // Deterministic
                GroupTail temp = (GroupTailtail;
                head =  = new GroupCurly(head.nextcurly.cmin,
                                   curly.cmaxcurly.type,
                                   ((GroupTail)tail).,
                                   ((GroupTail)tail).,
                                             capturingGroup);
                return head;
            } else { // Non-deterministic
                int temp = ((GroupHeadhead).;
                Loop loop;
                if (curly.type == )
                    loop = new Loop(this.temp);
                else  // Reluctant Curly
                    loop = new LazyLoop(this.temp);
                Prolog prolog = new Prolog(loop);
                this. += 1;
                loop.cmin = curly.cmin;
                loop.cmax = curly.cmax;
                loop.body = head;
                tail.next = loop;
                 = loop;
                return prolog// Dual return
            }
        }
        throw error("Internal logic error");
    }

    
Create group head and tail nodes using double return. If the group is created with anonymous true then it is a pure group and should not affect group counting.
    private Node createGroup(boolean anonymous) {
        int localIndex = ++;
        int groupIndex = 0;
        if (!anonymous)
            groupIndex = ++;
        GroupHead head = new GroupHead(localIndex);
         = new GroupTail(localIndexgroupIndex);
        if (!anonymous && groupIndex < 10)
            [groupIndex] = head;
        return head;
    }

    
Parses inlined match flags and set them appropriately.
    private void addFlag() {
        int ch = peek();
        for (;;) {
            switch (ch) {
            case 'i':
                 |= ;
                break;
            case 'm':
                 |= ;
                break;
            case 's':
                 |= ;
                break;
            case 'd':
                 |= ;
                break;
            case 'u':
                 |= ;
                break;
            case 'c':
                 |= ;
                break;
            case 'x':
                 |= ;
                break;
            case 'U':
                 |= ( | );
                break;
            case '-'// subFlag then fall through
                ch = next();
                subFlag();
            default:
                return;
            }
            ch = next();
        }
    }

    
Parses the second part of inlined match flags and turns off flags appropriately.
    private void subFlag() {
        int ch = peek();
        for (;;) {
            switch (ch) {
            case 'i':
                 &= ~;
                break;
            case 'm':
                 &= ~;
                break;
            case 's':
                 &= ~;
                break;
            case 'd':
                 &= ~;
                break;
            case 'u':
                 &= ~;
                break;
            case 'c':
                 &= ~;
                break;
            case 'x':
                 &= ~;
                break;
            case 'U':
                 &= ~( | );
            default:
                return;
            }
            ch = next();
        }
    }
    static final int MAX_REPS   = 0x7FFFFFFF;
    static final int GREEDY     = 0;
    static final int LAZY       = 1;
    static final int POSSESSIVE = 2;
    static final int INDEPENDENT = 3;

    
Processes repetition. If the next character peeked is a quantifier then new nodes must be appended to handle the repetition. Prev could be a single or a group, so it could be a chain of nodes.
    private Node closure(Node prev) {
        Node atom;
        int ch = peek();
        switch (ch) {
        case '?':
            ch = next();
            if (ch == '?') {
                next();
                return new Ques(prev);
            } else if (ch == '+') {
                next();
                return new Ques(prev);
            }
            return new Ques(prev);
        case '*':
            ch = next();
            if (ch == '?') {
                next();
                return new Curly(prev, 0, );
            } else if (ch == '+') {
                next();
                return new Curly(prev, 0, );
            }
            return new Curly(prev, 0, );
        case '+':
            ch = next();
            if (ch == '?') {
                next();
                return new Curly(prev, 1, );
            } else if (ch == '+') {
                next();
                return new Curly(prev, 1, );
            }
            return new Curly(prev, 1, );
        case '{':
            ch = [+1];
            if (ASCII.isDigit(ch)) {
                skip();
                int cmin = 0;
                do {
                    cmin = cmin * 10 + (ch - '0');
                } while (ASCII.isDigit(ch = read()));
                int cmax = cmin;
                if (ch == ',') {
                    ch = read();
                    cmax = ;
                    if (ch != '}') {
                        cmax = 0;
                        while (ASCII.isDigit(ch)) {
                            cmax = cmax * 10 + (ch - '0');
                            ch = read();
                        }
                    }
                }
                if (ch != '}')
                    throw error("Unclosed counted closure");
                if (((cmin) | (cmax) | (cmax - cmin)) < 0)
                    throw error("Illegal repetition range");
                Curly curly;
                ch = peek();
                if (ch == '?') {
                    next();
                    curly = new Curly(prevcmincmax);
                } else if (ch == '+') {
                    next();
                    curly = new Curly(prevcmincmax);
                } else {
                    curly = new Curly(prevcmincmax);
                }
                return curly;
            } else {
                throw error("Illegal repetition");
            }
        default:
            return prev;
        }
    }

    
Utility method for parsing control escape sequences.
    private int c() {
        if ( < ) {
            return read() ^ 64;
        }
        throw error("Illegal control escape sequence");
    }

    
Utility method for parsing octal escape sequences.
    private int o() {
        int n = read();
        if (((n-'0')|('7'-n)) >= 0) {
            int m = read();
            if (((m-'0')|('7'-m)) >= 0) {
                int o = read();
                if ((((o-'0')|('7'-o)) >= 0) && (((n-'0')|('3'-n)) >= 0)) {
                    return (n - '0') * 64 + (m - '0') * 8 + (o - '0');
                }
                unread();
                return (n - '0') * 8 + (m - '0');
            }
            unread();
            return (n - '0');
        }
        throw error("Illegal octal escape sequence");
    }

    
Utility method for parsing hexadecimal escape sequences.
    private int x() {
        int n = read();
        if (ASCII.isHexDigit(n)) {
            int m = read();
            if (ASCII.isHexDigit(m)) {
                return ASCII.toDigit(n) * 16 + ASCII.toDigit(m);
            }
        } else if (n == '{' && ASCII.isHexDigit(peek())) {
            int ch = 0;
            while (ASCII.isHexDigit(n = read())) {
                ch = (ch << 4) + ASCII.toDigit(n);
                if (ch > .)
                    throw error("Hexadecimal codepoint is too big");
            }
            if (n != '}')
                throw error("Unclosed hexadecimal escape sequence");
            return ch;
        }
        throw error("Illegal hexadecimal escape sequence");
    }

    
Utility method for parsing unicode escape sequences.
    private int cursor() {
        return ;
    }
    private void setcursor(int pos) {
         = pos;
    }
    private int uxxxx() {
        int n = 0;
        for (int i = 0; i < 4; i++) {
            int ch = read();
            if (!ASCII.isHexDigit(ch)) {
                throw error("Illegal Unicode escape sequence");
            }
            n = n * 16 + ASCII.toDigit(ch);
        }
        return n;
    }
    private int u() {
        int n = uxxxx();
        if (Character.isHighSurrogate((char)n)) {
            int cur = cursor();
            if (read() == '\\' && read() == 'u') {
                int n2 = uxxxx();
                if (Character.isLowSurrogate((char)n2))
                    return Character.toCodePoint((char)n, (char)n2);
            }
            setcursor(cur);
        }
        return n;
    }
    //
    // Utility methods for code point support
    //
    private static final int countChars(CharSequence seqint index,
                                        int lengthInCodePoints) {
        // optimization
        if (lengthInCodePoints == 1 && !Character.isHighSurrogate(seq.charAt(index))) {
            assert (index >= 0 && index < seq.length());
            return 1;
        }
        int length = seq.length();
        int x = index;
        if (lengthInCodePoints >= 0) {
            assert (index >= 0 && index < length);
            for (int i = 0; x < length && i < lengthInCodePointsi++) {
                if (Character.isHighSurrogate(seq.charAt(x++))) {
                    if (x < length && Character.isLowSurrogate(seq.charAt(x))) {
                        x++;
                    }
                }
            }
            return x - index;
        }
        assert (index >= 0 && index <= length);
        if (index == 0) {
            return 0;
        }
        int len = -lengthInCodePoints;
        for (int i = 0; x > 0 && i < leni++) {
            if (Character.isLowSurrogate(seq.charAt(--x))) {
                if (x > 0 && Character.isHighSurrogate(seq.charAt(x-1))) {
                    x--;
                }
            }
        }
        return index - x;
    }
    private static final int countCodePoints(CharSequence seq) {
        int length = seq.length();
        int n = 0;
        for (int i = 0; i < length; ) {
            n++;
            if (Character.isHighSurrogate(seq.charAt(i++))) {
                if (i < length && Character.isLowSurrogate(seq.charAt(i))) {
                    i++;
                }
            }
        }
        return n;
    }

    
Creates a bit vector for matching Latin-1 values. A normal BitClass never matches values above Latin-1, and a complemented BitClass always matches values above Latin-1.
    private static final class BitClass extends BmpCharProperty {
        final boolean[] bits;
        BitClass() {  = new boolean[256]; }
        private BitClass(boolean[] bits) { this. = bits; }
        BitClass add(int cint flags) {
            assert c >= 0 && c <= 255;
            if ((flags & ) != 0) {
                if (ASCII.isAscii(c)) {
                    [ASCII.toUpper(c)] = true;
                    [ASCII.toLower(c)] = true;
                } else if ((flags & ) != 0) {
                    [Character.toLowerCase(c)] = true;
                    [Character.toUpperCase(c)] = true;
                }
            }
            [c] = true;
            return this;
        }
        boolean isSatisfiedBy(int ch) {
            return ch < 256 && [ch];
        }
    }

    
Returns a suitably optimized, single character matcher.
    private CharProperty newSingle(final int ch) {
        if (has()) {
            int lowerupper;
            if (has()) {
                upper = Character.toUpperCase(ch);
                lower = Character.toLowerCase(upper);
                if (upper != lower)
                    return new SingleU(lower);
            } else if (ASCII.isAscii(ch)) {
                lower = ASCII.toLower(ch);
                upper = ASCII.toUpper(ch);
                if (lower != upper)
                    return new SingleI(lowerupper);
            }
        }
        if (isSupplementary(ch))
            return new SingleS(ch);    // Match a given Unicode character
        return new Single(ch);         // Match a given BMP character
    }

    
Utility method for creating a string slice matcher.
    private Node newSlice(int[] bufint countboolean hasSupplementary) {
        int[] tmp = new int[count];
        if (has()) {
            if (has()) {
                for (int i = 0; i < counti++) {
                    tmp[i] = Character.toLowerCase(
                                 Character.toUpperCase(buf[i]));
                }
                return hasSupplementarynew SliceUS(tmp) : new SliceU(tmp);
            }
            for (int i = 0; i < counti++) {
                tmp[i] = ASCII.toLower(buf[i]);
            }
            return hasSupplementarynew SliceIS(tmp) : new SliceI(tmp);
        }
        for (int i = 0; i < counti++) {
            tmp[i] = buf[i];
        }
        return hasSupplementary ? new SliceS(tmp) : new Slice(tmp);
    }

    
The following classes are the building components of the object tree that represents a compiled regular expression. The object tree is made of individual elements that handle constructs in the Pattern. Each type of object knows how to match its equivalent construct with the match() method.


    
Base class for all node classes. Subclasses should override the match() method as appropriate. This class is an accepting node, so its match() always returns true.
    static class Node extends Object {
        Node next;
        Node() {
             = .;
        }
        
This method implements the classic accept node.
        boolean match(Matcher matcherint iCharSequence seq) {
            matcher.last = i;
            matcher.groups[0] = matcher.first;
            matcher.groups[1] = matcher.last;
            return true;
        }
        
This method is good for all zero length assertions.
        boolean study(TreeInfo info) {
            if ( != null) {
                return .study(info);
            } else {
                return info.deterministic;
            }
        }
    }
    static class LastNode extends Node {
        
This method implements the classic accept node with the addition of a check to see if the match occurred using all of the input.
        boolean match(Matcher matcherint iCharSequence seq) {
            if (matcher.acceptMode == . && i != matcher.to)
                return false;
            matcher.last = i;
            matcher.groups[0] = matcher.first;
            matcher.groups[1] = matcher.last;
            return true;
        }
    }

    
Used for REs that can start anywhere within the input string. This basically tries to match repeatedly at each spot in the input string, moving forward after each try. An anchored search or a BnM will bypass this node completely.
    static class Start extends Node {
        int minLength;
        Start(Node node) {
            this. = node;
            TreeInfo info = new TreeInfo();
            .study(info);
             = info.minLength;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            if (i > matcher.to - ) {
                matcher.hitEnd = true;
                return false;
            }
            int guard = matcher.to - ;
            for (; i <= guardi++) {
                if (.match(matcheriseq)) {
                    matcher.first = i;
                    matcher.groups[0] = matcher.first;
                    matcher.groups[1] = matcher.last;
                    return true;
                }
            }
            matcher.hitEnd = true;
            return false;
        }
        boolean study(TreeInfo info) {
            .study(info);
            info.maxValid = false;
            info.deterministic = false;
            return false;
        }
    }
    /*
     * StartS supports supplementary characters, including unpaired surrogates.
     */
    static final class StartS extends Start {
        StartS(Node node) {
            super(node);
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            if (i > matcher.to - ) {
                matcher.hitEnd = true;
                return false;
            }
            int guard = matcher.to - ;
            while (i <= guard) {
                //if ((ret = next.match(matcher, i, seq)) || i == guard)
                if (.match(matcheriseq)) {
                    matcher.first = i;
                    matcher.groups[0] = matcher.first;
                    matcher.groups[1] = matcher.last;
                    return true;
                }
                if (i == guard)
                    break;
                // Optimization to move to the next character. This is
                // faster than countChars(seq, i, 1).
                if (Character.isHighSurrogate(seq.charAt(i++))) {
                    if (i < seq.length() &&
                        Character.isLowSurrogate(seq.charAt(i))) {
                        i++;
                    }
                }
            }
            matcher.hitEnd = true;
            return false;
        }
    }

    
Node to anchor at the beginning of input. This object implements the match for a \A sequence, and the caret anchor will use this if not in multiline mode.
    static final class Begin extends Node {
        boolean match(Matcher matcherint iCharSequence seq) {
            int fromIndex = (matcher.anchoringBounds) ?
                matcher.from : 0;
            if (i == fromIndex && .match(matcheriseq)) {
                matcher.first = i;
                matcher.groups[0] = i;
                matcher.groups[1] = matcher.last;
                return true;
            } else {
                return false;
            }
        }
    }

    
Node to anchor at the end of input. This is the absolute end, so this should not match at the last newline before the end as $ will.
    static final class End extends Node {
        boolean match(Matcher matcherint iCharSequence seq) {
            int endIndex = (matcher.anchoringBounds) ?
                matcher.to : matcher.getTextLength();
            if (i == endIndex) {
                matcher.hitEnd = true;
                return .match(matcheriseq);
            }
            return false;
        }
    }

    
Node to anchor at the beginning of a line. This is essentially the object to match for the multiline ^.
    static final class Caret extends Node {
        boolean match(Matcher matcherint iCharSequence seq) {
            int startIndex = matcher.from;
            int endIndex = matcher.to;
            if (!matcher.anchoringBounds) {
                startIndex = 0;
                endIndex = matcher.getTextLength();
            }
            // Perl does not match ^ at end of input even after newline
            if (i == endIndex) {
                matcher.hitEnd = true;
                return false;
            }
            if (i > startIndex) {
                char ch = seq.charAt(i-1);
                if (ch != '\n' && ch != '\r'
                    && (ch|1) != '\u2029'
                    && ch != '\u0085' ) {
                    return false;
                }
                // Should treat /r/n as one newline
                if (ch == '\r' && seq.charAt(i) == '\n')
                    return false;
            }
            return .match(matcheriseq);
        }
    }

    
Node to anchor at the beginning of a line when in unixdot mode.
    static final class UnixCaret extends Node {
        boolean match(Matcher matcherint iCharSequence seq) {
            int startIndex = matcher.from;
            int endIndex = matcher.to;
            if (!matcher.anchoringBounds) {
                startIndex = 0;
                endIndex = matcher.getTextLength();
            }
            // Perl does not match ^ at end of input even after newline
            if (i == endIndex) {
                matcher.hitEnd = true;
                return false;
            }
            if (i > startIndex) {
                char ch = seq.charAt(i-1);
                if (ch != '\n') {
                    return false;
                }
            }
            return .match(matcheriseq);
        }
    }

    
Node to match the location where the last match ended. This is used for the \G construct.
    static final class LastMatch extends Node {
        boolean match(Matcher matcherint iCharSequence seq) {
            if (i != matcher.oldLast)
                return false;
            return .match(matcheriseq);
        }
    }

    
Node to anchor at the end of a line or the end of input based on the multiline mode. When not in multiline mode, the $ can only match at the very end of the input, unless the input ends in a line terminator in which it matches right before the last line terminator. Note that \r\n is considered an atomic line terminator. Like ^ the $ operator matches at a position, it does not match the line terminators themselves.
    static final class Dollar extends Node {
        boolean multiline;
        Dollar(boolean mul) {
             = mul;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int endIndex = (matcher.anchoringBounds) ?
                matcher.to : matcher.getTextLength();
            if (!) {
                if (i < endIndex - 2)
                    return false;
                if (i == endIndex - 2) {
                    char ch = seq.charAt(i);
                    if (ch != '\r')
                        return false;
                    ch = seq.charAt(i + 1);
                    if (ch != '\n')
                        return false;
                }
            }
            // Matches before any line terminator; also matches at the
            // end of input
            // Before line terminator:
            // If multiline, we match here no matter what
            // If not multiline, fall through so that the end
            // is marked as hit; this must be a /r/n or a /n
            // at the very end so the end was hit; more input
            // could make this not match here
            if (i < endIndex) {
                char ch = seq.charAt(i);
                 if (ch == '\n') {
                     // No match between \r\n
                     if (i > 0 && seq.charAt(i-1) == '\r')
                         return false;
                     if ()
                         return .match(matcheriseq);
                 } else if (ch == '\r' || ch == '\u0085' ||
                            (ch|1) == '\u2029') {
                     if ()
                         return .match(matcheriseq);
                 } else { // No line terminator, no match
                     return false;
                 }
            }
            // Matched at current end so hit end
            matcher.hitEnd = true;
            // If a $ matches because of end of input, then more input
            // could cause it to fail!
            matcher.requireEnd = true;
            return .match(matcheriseq);
        }
        boolean study(TreeInfo info) {
            .study(info);
            return info.deterministic;
        }
    }

    
Node to anchor at the end of a line or the end of input based on the multiline mode when in unix lines mode.
    static final class UnixDollar extends Node {
        boolean multiline;
        UnixDollar(boolean mul) {
             = mul;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int endIndex = (matcher.anchoringBounds) ?
                matcher.to : matcher.getTextLength();
            if (i < endIndex) {
                char ch = seq.charAt(i);
                if (ch == '\n') {
                    // If not multiline, then only possible to
                    // match at very end or one before end
                    if ( == false && i != endIndex - 1)
                        return false;
                    // If multiline return next.match without setting
                    // matcher.hitEnd
                    if ()
                        return .match(matcheriseq);
                } else {
                    return false;
                }
            }
            // Matching because at the end or 1 before the end;
            // more input could change this so set hitEnd
            matcher.hitEnd = true;
            // If a $ matches because of end of input, then more input
            // could cause it to fail!
            matcher.requireEnd = true;
            return .match(matcheriseq);
        }
        boolean study(TreeInfo info) {
            .study(info);
            return info.deterministic;
        }
    }

    
Abstract node class to match one character satisfying some boolean property.
    private static abstract class CharProperty extends Node {
        abstract boolean isSatisfiedBy(int ch);
        CharProperty complement() {
            return new CharProperty() {
                    boolean isSatisfiedBy(int ch) {
                        return ! CharProperty.this.isSatisfiedBy(ch);}};
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            if (i < matcher.to) {
                int ch = Character.codePointAt(seqi);
                return isSatisfiedBy(ch)
                    && .match(matcheri+Character.charCount(ch), seq);
            } else {
                matcher.hitEnd = true;
                return false;
            }
        }
        boolean study(TreeInfo info) {
            info.minLength++;
            info.maxLength++;
            return .study(info);
        }
    }

    
Optimized version of CharProperty that works only for properties never satisfied by Supplementary characters.
    private static abstract class BmpCharProperty extends CharProperty {
        boolean match(Matcher matcherint iCharSequence seq) {
            if (i < matcher.to) {
                return isSatisfiedBy(seq.charAt(i))
                    && .match(matcheri+1, seq);
            } else {
                matcher.hitEnd = true;
                return false;
            }
        }
    }

    
Node class that matches a Supplementary Unicode character
    static final class SingleS extends CharProperty {
        final int c;
        SingleS(int c) { this. = c; }
        boolean isSatisfiedBy(int ch) {
            return ch == ;
        }
    }

    
Optimization -- matches a given BMP character
    static final class Single extends BmpCharProperty {
        final int c;
        Single(int c) { this. = c; }
        boolean isSatisfiedBy(int ch) {
            return ch == ;
        }
    }

    
Case insensitive matches a given BMP character
    static final class SingleI extends BmpCharProperty {
        final int lower;
        final int upper;
        SingleI(int lowerint upper) {
            this. = lower;
            this. = upper;
        }
        boolean isSatisfiedBy(int ch) {
            return ch ==  || ch == ;
        }
    }

    
Unicode case insensitive matches a given Unicode character
    static final class SingleU extends CharProperty {
        final int lower;
        SingleU(int lower) {
            this. = lower;
        }
        boolean isSatisfiedBy(int ch) {
            return  == ch ||
                 == Character.toLowerCase(Character.toUpperCase(ch));
        }
    }


    
Node class that matches a Unicode block.
    static final class Block extends CharProperty {
        final Character.UnicodeBlock block;
        Block(Character.UnicodeBlock block) {
            this. = block;
        }
        boolean isSatisfiedBy(int ch) {
            return  == Character.UnicodeBlock.of(ch);
        }
    }

    
Node class that matches a Unicode script
    static final class Script extends CharProperty {
        final Character.UnicodeScript script;
        Script(Character.UnicodeScript script) {
            this. = script;
        }
        boolean isSatisfiedBy(int ch) {
            return  == Character.UnicodeScript.of(ch);
        }
    }

    
Node class that matches a Unicode category.
    static final class Category extends CharProperty {
        final int typeMask;
        Category(int typeMask) { this. = typeMask; }
        boolean isSatisfiedBy(int ch) {
            return ( & (1 << Character.getType(ch))) != 0;
        }
    }

    
Node class that matches a Unicode "type"
    static final class Utype extends CharProperty {
        final UnicodeProp uprop;
        Utype(UnicodeProp uprop) { this. = uprop; }
        boolean isSatisfiedBy(int ch) {
            return .is(ch);
        }
    }


    
Node class that matches a POSIX type.
    static final class Ctype extends BmpCharProperty {
        final int ctype;
        Ctype(int ctype) { this. = ctype; }
        boolean isSatisfiedBy(int ch) {
            return ch < 128 && ASCII.isType(ch);
        }
    }

    
Base class for all Slice nodes
    static class SliceNode extends Node {
        int[] buffer;
        SliceNode(int[] buf) {
             = buf;
        }
        boolean study(TreeInfo info) {
            info.minLength += .;
            info.maxLength += .;
            return .study(info);
        }
    }

    
Node class for a case sensitive/BMP-only sequence of literal characters.
    static final class Slice extends SliceNode {
        Slice(int[] buf) {
            super(buf);
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int[] buf = ;
            int len = buf.length;
            for (int j=0; j<lenj++) {
                if ((i+j) >= matcher.to) {
                    matcher.hitEnd = true;
                    return false;
                }
                if (buf[j] != seq.charAt(i+j))
                    return false;
            }
            return .match(matcheri+lenseq);
        }
    }

    
Node class for a case_insensitive/BMP-only sequence of literal characters.
    static class SliceI extends SliceNode {
        SliceI(int[] buf) {
            super(buf);
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int[] buf = ;
            int len = buf.length;
            for (int j=0; j<lenj++) {
                if ((i+j) >= matcher.to) {
                    matcher.hitEnd = true;
                    return false;
                }
                int c = seq.charAt(i+j);
                if (buf[j] != c &&
                    buf[j] != ASCII.toLower(c))
                    return false;
            }
            return .match(matcheri+lenseq);
        }
    }

    
Node class for a unicode_case_insensitive/BMP-only sequence of literal characters. Uses unicode case folding.
    static final class SliceU extends SliceNode {
        SliceU(int[] buf) {
            super(buf);
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int[] buf = ;
            int len = buf.length;
            for (int j=0; j<lenj++) {
                if ((i+j) >= matcher.to) {
                    matcher.hitEnd = true;
                    return false;
                }
                int c = seq.charAt(i+j);
                if (buf[j] != c &&
                    buf[j] != Character.toLowerCase(Character.toUpperCase(c)))
                    return false;
            }
            return .match(matcheri+lenseq);
        }
    }

    
Node class for a case sensitive sequence of literal characters including supplementary characters.
    static final class SliceS extends SliceNode {
        SliceS(int[] buf) {
            super(buf);
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int[] buf = ;
            int x = i;
            for (int j = 0; j < buf.lengthj++) {
                if (x >= matcher.to) {
                    matcher.hitEnd = true;
                    return false;
                }
                int c = Character.codePointAt(seqx);
                if (buf[j] != c)
                    return false;
                x += Character.charCount(c);
                if (x > matcher.to) {
                    matcher.hitEnd = true;
                    return false;
                }
            }
            return .match(matcherxseq);
        }
    }

    
Node class for a case insensitive sequence of literal characters including supplementary characters.
    static class SliceIS extends SliceNode {
        SliceIS(int[] buf) {
            super(buf);
        }
        int toLower(int c) {
            return ASCII.toLower(c);
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int[] buf = ;
            int x = i;
            for (int j = 0; j < buf.lengthj++) {
                if (x >= matcher.to) {
                    matcher.hitEnd = true;
                    return false;
                }
                int c = Character.codePointAt(seqx);
                if (buf[j] != c && buf[j] != toLower(c))
                    return false;
                x += Character.charCount(c);
                if (x > matcher.to) {
                    matcher.hitEnd = true;
                    return false;
                }
            }
            return .match(matcherxseq);
        }
    }

    
Node class for a case insensitive sequence of literal characters. Uses unicode case folding.
    static final class SliceUS extends SliceIS {
        SliceUS(int[] buf) {
            super(buf);
        }
        int toLower(int c) {
            return Character.toLowerCase(Character.toUpperCase(c));
        }
    }
    private static boolean inRange(int lowerint chint upper) {
        return lower <= ch && ch <= upper;
    }

    
Returns node for matching characters within an explicit value range.
    private static CharProperty rangeFor(final int lower,
                                         final int upper) {
        return new CharProperty() {
                boolean isSatisfiedBy(int ch) {
                    return inRange(lowerchupper);}};
    }

    
Returns node for matching characters within an explicit value range in a case insensitive manner.
    private CharProperty caseInsensitiveRangeFor(final int lower,
                                                 final int upper) {
        if (has())
            return new CharProperty() {
                boolean isSatisfiedBy(int ch) {
                    if (inRange(lowerchupper))
                        return true;
                    int up = Character.toUpperCase(ch);
                    return inRange(lowerupupper) ||
                           inRange(lower, Character.toLowerCase(up), upper);}};
        return new CharProperty() {
            boolean isSatisfiedBy(int ch) {
                return inRange(lowerchupper) ||
                    ASCII.isAscii(ch) &&
                        (inRange(lower, ASCII.toUpper(ch), upper) ||
                         inRange(lower, ASCII.toLower(ch), upper));
            }};
    }

    
Implements the Unicode category ALL and the dot metacharacter when in dotall mode.
    static final class All extends CharProperty {
        boolean isSatisfiedBy(int ch) {
            return true;
        }
    }

    
Node class for the dot metacharacter when dotall is not enabled.
    static final class Dot extends CharProperty {
        boolean isSatisfiedBy(int ch) {
            return (ch != '\n' && ch != '\r'
                    && (ch|1) != '\u2029'
                    && ch != '\u0085');
        }
    }

    
Node class for the dot metacharacter when dotall is not enabled but UNIX_LINES is enabled.
    static final class UnixDot extends CharProperty {
        boolean isSatisfiedBy(int ch) {
            return ch != '\n';
        }
    }

    
The 0 or 1 quantifier. This one class implements all three types.
    static final class Ques extends Node {
        Node atom;
        int type;
        Ques(Node nodeint type) {
            this. = node;
            this. = type;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            switch () {
            case :
                return (.match(matcheriseq) && .match(matchermatcher.lastseq))
                    || .match(matcheriseq);
            case :
                return .match(matcheriseq)
                    || (.match(matcheriseq) && .match(matchermatcher.lastseq));
            case :
                if (.match(matcheriseq)) i = matcher.last;
                return .match(matcheriseq);
            default:
                return .match(matcheriseq) && .match(matchermatcher.lastseq);
            }
        }
        boolean study(TreeInfo info) {
            if ( != ) {
                int minL = info.minLength;
                .study(info);
                info.minLength = minL;
                info.deterministic = false;
                return .study(info);
            } else {
                .study(info);
                return .study(info);
            }
        }
    }

    
Handles the curly-brace style repetition with a specified minimum and maximum occurrences. The * quantifier is handled as a special case. This class handles the three types.
    static final class Curly extends Node {
        Node atom;
        int type;
        int cmin;
        int cmax;
        Curly(Node nodeint cminint cmaxint type) {
            this. = node;
            this. = type;
            this. = cmin;
            this. = cmax;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int j;
            for (j = 0; j < j++) {
                if (.match(matcheriseq)) {
                    i = matcher.last;
                    continue;
                }
                return false;
            }
            if ( == )
                return match0(matcherijseq);
            else if ( == )
                return match1(matcherijseq);
            else
                return match2(matcherijseq);
        }
        // Greedy match.
        // i is the index to start matching at
        // j is the number of atoms that have matched
        boolean match0(Matcher matcherint iint jCharSequence seq) {
            if (j >= ) {
                // We have matched the maximum... continue with the rest of
                // the regular expression
                return .match(matcheriseq);
            }
            int backLimit = j;
            while (.match(matcheriseq)) {
                // k is the length of this match
                int k = matcher.last - i;
                if (k == 0) // Zero length match
                    break;
                // Move up index and number matched
                i = matcher.last;
                j++;
                // We are greedy so match as many as we can
                while (j < ) {
                    if (!.match(matcheriseq))
                        break;
                    if (i + k != matcher.last) {
                        if (match0(matchermatcher.lastj+1, seq))
                            return true;
                        break;
                    }
                    i += k;
                    j++;
                }
                // Handle backing off if match fails
                while (j >= backLimit) {
                   if (.match(matcheriseq))
                        return true;
                    i -= k;
                    j--;
                }
                return false;
            }
            return .match(matcheriseq);
        }
        // Reluctant match. At this point, the minimum has been satisfied.
        // i is the index to start matching at
        // j is the number of atoms that have matched
        boolean match1(Matcher matcherint iint jCharSequence seq) {
            for (;;) {
                // Try finishing match without consuming any more
                if (.match(matcheriseq))
                    return true;
                // At the maximum, no match found
                if (j >= )
                    return false;
                // Okay, must try one more atom
                if (!.match(matcheriseq))
                    return false;
                // If we haven't moved forward then must break out
                if (i == matcher.last)
                    return false;
                // Move up index and number matched
                i = matcher.last;
                j++;
            }
        }
        boolean match2(Matcher matcherint iint jCharSequence seq) {
            for (; j < j++) {
                if (!.match(matcheriseq))
                    break;
                if (i == matcher.last)
                    break;
                i = matcher.last;
            }
            return .match(matcheriseq);
        }
        boolean study(TreeInfo info) {
            // Save original info
            int minL = info.minLength;
            int maxL = info.maxLength;
            boolean maxV = info.maxValid;
            boolean detm = info.deterministic;
            info.reset();
            .study(info);
            int temp = info.minLength *  + minL;
            if (temp < minL) {
                temp = 0xFFFFFFF; // arbitrary large number
            }
            info.minLength = temp;
            if (maxV & info.maxValid) {
                temp = info.maxLength *  + maxL;
                info.maxLength = temp;
                if (temp < maxL) {
                    info.maxValid = false;
                }
            } else {
                info.maxValid = false;
            }
            if (info.deterministic &&  == )
                info.deterministic = detm;
            else
                info.deterministic = false;
            return .study(info);
        }
    }

    
Handles the curly-brace style repetition with a specified minimum and maximum occurrences in deterministic cases. This is an iterative optimization over the Prolog and Loop system which would handle this in a recursive way. The * quantifier is handled as a special case. If capture is true then this class saves group settings and ensures that groups are unset when backing off of a group match.
    static final class GroupCurly extends Node {
        Node atom;
        int type;
        int cmin;
        int cmax;
        int localIndex;
        int groupIndex;
        boolean capture;
        GroupCurly(Node nodeint cminint cmaxint typeint local,
                   int groupboolean capture) {
            this. = node;
            this. = type;
            this. = cmin;
            this. = cmax;
            this. = local;
            this. = group;
            this. = capture;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int[] groups = matcher.groups;
            int[] locals = matcher.locals;
            int save0 = locals[];
            int save1 = 0;
            int save2 = 0;
            if () {
                save1 = groups[];
                save2 = groups[+1];
            }
            // Notify GroupTail there is no need to setup group info
            // because it will be set here
            locals[] = -1;
            boolean ret = true;
            for (int j = 0; j < j++) {
                if (.match(matcheriseq)) {
                    if () {
                        groups[] = i;
                        groups[+1] = matcher.last;
                    }
                    i = matcher.last;
                } else {
                    ret = false;
                    break;
                }
            }
            if (ret) {
                if ( == ) {
                    ret = match0(matcheriseq);
                } else if ( == ) {
                    ret = match1(matcheriseq);
                } else {
                    ret = match2(matcheriseq);
                }
            }
            if (!ret) {
                locals[] = save0;
                if () {
                    groups[] = save1;
                    groups[+1] = save2;
                }
            }
            return ret;
        }
        // Aggressive group match
        boolean match0(Matcher matcherint iint jCharSequence seq) {
            int[] groups = matcher.groups;
            int save0 = 0;
            int save1 = 0;
            if () {
                save0 = groups[];
                save1 = groups[+1];
            }
            for (;;) {
                if (j >= )
                    break;
                if (!.match(matcheriseq))
                    break;
                int k = matcher.last - i;
                if (k <= 0) {
                    if () {
                        groups[] = i;
                        groups[+1] = i + k;
                    }
                    i = i + k;
                    break;
                }
                for (;;) {
                    if () {
                        groups[] = i;
                        groups[+1] = i + k;
                    }
                    i = i + k;
                    if (++j >= )
                        break;
                    if (!.match(matcheriseq))
                        break;
                    if (i + k != matcher.last) {
                        if (match0(matcherijseq))
                            return true;
                        break;
                    }
                }
                while (j > ) {
                    if (.match(matcheriseq)) {
                        if () {
                            groups[+1] = i;
                            groups[] = i - k;
                        }
                        i = i - k;
                        return true;
                    }
                    // backing off
                    if () {
                        groups[+1] = i;
                        groups[] = i - k;
                    }
                    i = i - k;
                    j--;
                }
                break;
            }
            if () {
                groups[] = save0;
                groups[+1] = save1;
            }
            return .match(matcheriseq);
        }
        // Reluctant matching
        boolean match1(Matcher matcherint iint jCharSequence seq) {
            for (;;) {
                if (.match(matcheriseq))
                    return true;
                if (j >= )
                    return false;
                if (!.match(matcheriseq))
                    return false;
                if (i == matcher.last)
                    return false;
                if () {
                    matcher.groups[] = i;
                    matcher.groups[+1] = matcher.last;
                }
                i = matcher.last;
                j++;
            }
        }
        // Possessive matching
        boolean match2(Matcher matcherint iint jCharSequence seq) {
            for (; j < j++) {
                if (!.match(matcheriseq)) {
                    break;
                }
                if () {
                    matcher.groups[] = i;
                    matcher.groups[+1] = matcher.last;
                }
                if (i == matcher.last) {
                    break;
                }
                i = matcher.last;
            }
            return .match(matcheriseq);
        }
        boolean study(TreeInfo info) {
            // Save original info
            int minL = info.minLength;
            int maxL = info.maxLength;
            boolean maxV = info.maxValid;
            boolean detm = info.deterministic;
            info.reset();
            .study(info);
            int temp = info.minLength *  + minL;
            if (temp < minL) {
                temp = 0xFFFFFFF; // Arbitrary large number
            }
            info.minLength = temp;
            if (maxV & info.maxValid) {
                temp = info.maxLength *  + maxL;
                info.maxLength = temp;
                if (temp < maxL) {
                    info.maxValid = false;
                }
            } else {
                info.maxValid = false;
            }
            if (info.deterministic &&  == ) {
                info.deterministic = detm;
            } else {
                info.deterministic = false;
            }
            return .study(info);
        }
    }

    
A Guard node at the end of each atom node in a Branch. It serves the purpose of chaining the "match" operation to "next" but not the "study", so we can collect the TreeInfo of each atom node without including the TreeInfo of the "next".
    static final class BranchConn extends Node {
        BranchConn() {};
        boolean match(Matcher matcherint iCharSequence seq) {
            return .match(matcheriseq);
        }
        boolean study(TreeInfo info) {
            return info.deterministic;
        }
    }

    
Handles the branching of alternations. Note this is also used for the ? quantifier to branch between the case where it matches once and where it does not occur.
    static final class Branch extends Node {
        Node[] atoms = new Node[2];
        int size = 2;
        Node conn;
        Branch(Node firstNode secondNode branchConn) {
             = branchConn;
            [0] = first;
            [1] = second;
        }
        void add(Node node) {
            if ( >= .) {
                Node[] tmp = new Node[.*2];
                System.arraycopy(, 0, tmp, 0, .);
                 = tmp;
            }
            [++] = node;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            for (int n = 0; n < n++) {
                if ([n] == null) {
                    if (..match(matcheriseq))
                        return true;
                } else if ([n].match(matcheriseq)) {
                    return true;
                }
            }
            return false;
        }
        boolean study(TreeInfo info) {
            int minL = info.minLength;
            int maxL = info.maxLength;
            boolean maxV = info.maxValid;
            int minL2 = .//arbitrary large enough num
            int maxL2 = -1;
            for (int n = 0; n < n++) {
                info.reset();
                if ([n] != null)
                    [n].study(info);
                minL2 = Math.min(minL2info.minLength);
                maxL2 = Math.max(maxL2info.maxLength);
                maxV = (maxV & info.maxValid);
            }
            minL += minL2;
            maxL += maxL2;
            info.reset();
            ..study(info);
            info.minLength += minL;
            info.maxLength += maxL;
            info.maxValid &= maxV;
            info.deterministic = false;
            return false;
        }
    }

    
The GroupHead saves the location where the group begins in the locals and restores them when the match is done. The matchRef is used when a reference to this group is accessed later in the expression. The locals will have a negative value in them to indicate that we do not want to unset the group if the reference doesn't match.
    static final class GroupHead extends Node {
        int localIndex;
        GroupHead(int localCount) {
             = localCount;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int save = matcher.locals[];
            matcher.locals[] = i;
            boolean ret = .match(matcheriseq);
            matcher.locals[] = save;
            return ret;
        }
        boolean matchRef(Matcher matcherint iCharSequence seq) {
            int save = matcher.locals[];
            matcher.locals[] = ~i// HACK
            boolean ret = .match(matcheriseq);
            matcher.locals[] = save;
            return ret;
        }
    }

    
Recursive reference to a group in the regular expression. It calls matchRef because if the reference fails to match we would not unset the group.
    static final class GroupRef extends Node {
        GroupHead head;
        GroupRef(GroupHead head) {
            this. = head;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            return .matchRef(matcheriseq)
                && .match(matchermatcher.lastseq);
        }
        boolean study(TreeInfo info) {
            info.maxValid = false;
            info.deterministic = false;
            return .study(info);
        }
    }

    
The GroupTail handles the setting of group beginning and ending locations when groups are successfully matched. It must also be able to unset groups that have to be backed off of. The GroupTail node is also used when a previous group is referenced, and in that case no group information needs to be set.
    static final class GroupTail extends Node {
        int localIndex;
        int groupIndex;
        GroupTail(int localCountint groupCount) {
             = localCount;
             = groupCount + groupCount;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int tmp = matcher.locals[];
            if (tmp >= 0) { // This is the normal group case.
                // Save the group so we can unset it if it
                // backs off of a match.
                int groupStart = matcher.groups[];
                int groupEnd = matcher.groups[+1];
                matcher.groups[] = tmp;
                matcher.groups[+1] = i;
                if (.match(matcheriseq)) {
                    return true;
                }
                matcher.groups[] = groupStart;
                matcher.groups[+1] = groupEnd;
                return false;
            } else {
                // This is a group reference case. We don't need to save any
                // group info because it isn't really a group.
                matcher.last = i;
                return true;
            }
        }
    }

    
This sets up a loop to handle a recursive quantifier structure.
    static final class Prolog extends Node {
        Loop loop;
        Prolog(Loop loop) {
            this. = loop;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            return .matchInit(matcheriseq);
        }
        boolean study(TreeInfo info) {
            return .study(info);
        }
    }

    
Handles the repetition count for a greedy Curly. The matchInit is called from the Prolog to save the index of where the group beginning is stored. A zero length group check occurs in the normal match but is skipped in the matchInit.
    static class Loop extends Node {
        Node body;
        int countIndex// local count index in matcher locals
        int beginIndex// group beginning index
        int cmincmax;
        Loop(int countIndexint beginIndex) {
            this. = countIndex;
            this. = beginIndex;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            // Avoid infinite loop in zero-length case.
            if (i > matcher.locals[]) {
                int count = matcher.locals[];
                // This block is for before we reach the minimum
                // iterations required for the loop to match
                if (count < ) {
                    matcher.locals[] = count + 1;
                    boolean b = .match(matcheriseq);
                    // If match failed we must backtrack, so
                    // the loop count should NOT be incremented
                    if (!b)
                        matcher.locals[] = count;
                    // Return success or failure since we are under
                    // minimum
                    return b;
                }
                // This block is for after we have the minimum
                // iterations required for the loop to match
                if (count < ) {
                    matcher.locals[] = count + 1;
                    boolean b = .match(matcheriseq);
                    // If match failed we must backtrack, so
                    // the loop count should NOT be incremented
                    if (!b)
                        matcher.locals[] = count;
                    else
                        return true;
                }
            }
            return .match(matcheriseq);
        }
        boolean matchInit(Matcher matcherint iCharSequence seq) {
            int save = matcher.locals[];
            boolean ret = false;
            if (0 < ) {
                matcher.locals[] = 1;
                ret = .match(matcheriseq);
            } else if (0 < ) {
                matcher.locals[] = 1;
                ret = .match(matcheriseq);
                if (ret == false)
                    ret = .match(matcheriseq);
            } else {
                ret = .match(matcheriseq);
            }
            matcher.locals[] = save;
            return ret;
        }
        boolean study(TreeInfo info) {
            info.maxValid = false;
            info.deterministic = false;
            return false;
        }
    }

    
Handles the repetition count for a reluctant Curly. The matchInit is called from the Prolog to save the index of where the group beginning is stored. A zero length group check occurs in the normal match but is skipped in the matchInit.
    static final class LazyLoop extends Loop {
        LazyLoop(int countIndexint beginIndex) {
            super(countIndexbeginIndex);
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            // Check for zero length group
            if (i > matcher.locals[]) {
                int count = matcher.locals[];
                if (count < ) {
                    matcher.locals[] = count + 1;
                    boolean result = .match(matcheriseq);
                    // If match failed we must backtrack, so
                    // the loop count should NOT be incremented
                    if (!result)
                        matcher.locals[] = count;
                    return result;
                }
                if (.match(matcheriseq))
                    return true;
                if (count < ) {
                    matcher.locals[] = count + 1;
                    boolean result = .match(matcheriseq);
                    // If match failed we must backtrack, so
                    // the loop count should NOT be incremented
                    if (!result)
                        matcher.locals[] = count;
                    return result;
                }
                return false;
            }
            return .match(matcheriseq);
        }
        boolean matchInit(Matcher matcherint iCharSequence seq) {
            int save = matcher.locals[];
            boolean ret = false;
            if (0 < ) {
                matcher.locals[] = 1;
                ret = .match(matcheriseq);
            } else if (.match(matcheriseq)) {
                ret = true;
            } else if (0 < ) {
                matcher.locals[] = 1;
                ret = .match(matcheriseq);
            }
            matcher.locals[] = save;
            return ret;
        }
        boolean study(TreeInfo info) {
            info.maxValid = false;
            info.deterministic = false;
            return false;
        }
    }

    
Refers to a group in the regular expression. Attempts to match whatever the group referred to last matched.
    static class BackRef extends Node {
        int groupIndex;
        BackRef(int groupCount) {
            super();
             = groupCount + groupCount;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int j = matcher.groups[];
            int k = matcher.groups[+1];
            int groupSize = k - j;
            // If the referenced group didn't match, neither can this
            if (j < 0)
                return false;
            // If there isn't enough input left no match
            if (i + groupSize > matcher.to) {
                matcher.hitEnd = true;
                return false;
            }
            // Check each new char to make sure it matches what the group
            // referenced matched last time around
            for (int index=0; index<groupSizeindex++)
                if (seq.charAt(i+index) != seq.charAt(j+index))
                    return false;
            return .match(matcheri+groupSizeseq);
        }
        boolean study(TreeInfo info) {
            info.maxValid = false;
            return .study(info);
        }
    }
    static class CIBackRef extends Node {
        int groupIndex;
        boolean doUnicodeCase;
        CIBackRef(int groupCountboolean doUnicodeCase) {
            super();
             = groupCount + groupCount;
            this. = doUnicodeCase;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int j = matcher.groups[];
            int k = matcher.groups[+1];
            int groupSize = k - j;
            // If the referenced group didn't match, neither can this
            if (j < 0)
                return false;
            // If there isn't enough input left no match
            if (i + groupSize > matcher.to) {
                matcher.hitEnd = true;
                return false;
            }
            // Check each new char to make sure it matches what the group
            // referenced matched last time around
            int x = i;
            for (int index=0; index<groupSizeindex++) {
                int c1 = Character.codePointAt(seqx);
                int c2 = Character.codePointAt(seqj);
                if (c1 != c2) {
                    if () {
                        int cc1 = Character.toUpperCase(c1);
                        int cc2 = Character.toUpperCase(c2);
                        if (cc1 != cc2 &&
                            Character.toLowerCase(cc1) !=
                            Character.toLowerCase(cc2))
                            return false;
                    } else {
                        if (ASCII.toLower(c1) != ASCII.toLower(c2))
                            return false;
                    }
                }
                x += Character.charCount(c1);
                j += Character.charCount(c2);
            }
            return .match(matcheri+groupSizeseq);
        }
        boolean study(TreeInfo info) {
            info.maxValid = false;
            return .study(info);
        }
    }

    
Searches until the next instance of its atom. This is useful for finding the atom efficiently without passing an instance of it (greedy problem) and without a lot of wasted search time (reluctant problem).
    static final class First extends Node {
        Node atom;
        First(Node node) {
            this. = BnM.optimize(node);
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            if ( instanceof BnM) {
                return .match(matcheriseq)
                    && .match(matchermatcher.lastseq);
            }
            for (;;) {
                if (i > matcher.to) {
                    matcher.hitEnd = true;
                    return false;
                }
                if (.match(matcheriseq)) {
                    return .match(matchermatcher.lastseq);
                }
                i += countChars(seqi, 1);
                matcher.first++;
            }
        }
        boolean study(TreeInfo info) {
            .study(info);
            info.maxValid = false;
            info.deterministic = false;
            return .study(info);
        }
    }
    static final class Conditional extends Node {
        Node condyesnot;
        Conditional(Node condNode yesNode not) {
            this. = cond;
            this. = yes;
            this. = not;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            if (.match(matcheriseq)) {
                return .match(matcheriseq);
            } else {
                return .match(matcheriseq);
            }
        }
        boolean study(TreeInfo info) {
            int minL = info.minLength;
            int maxL = info.maxLength;
            boolean maxV = info.maxValid;
            info.reset();
            .study(info);
            int minL2 = info.minLength;
            int maxL2 = info.maxLength;
            boolean maxV2 = info.maxValid;
            info.reset();
            .study(info);
            info.minLength = minL + Math.min(minL2info.minLength);
            info.maxLength = maxL + Math.max(maxL2info.maxLength);
            info.maxValid = (maxV & maxV2 & info.maxValid);
            info.deterministic = false;
            return .study(info);
        }
    }

    
Zero width positive lookahead.
    static final class Pos extends Node {
        Node cond;
        Pos(Node cond) {
            this. = cond;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int savedTo = matcher.to;
            boolean conditionMatched = false;
            // Relax transparent region boundaries for lookahead
            if (matcher.transparentBounds)
                matcher.to = matcher.getTextLength();
            try {
                conditionMatched = .match(matcheriseq);
            } finally {
                // Reinstate region boundaries
                matcher.to = savedTo;
            }
            return conditionMatched && .match(matcheriseq);
        }
    }

    
Zero width negative lookahead.
    static final class Neg extends Node {
        Node cond;
        Neg(Node cond) {
            this. = cond;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int savedTo = matcher.to;
            boolean conditionMatched = false;
            // Relax transparent region boundaries for lookahead
            if (matcher.transparentBounds)
                matcher.to = matcher.getTextLength();
            try {
                if (i < matcher.to) {
                    conditionMatched = !.match(matcheriseq);
                } else {
                    // If a negative lookahead succeeds then more input
                    // could cause it to fail!
                    matcher.requireEnd = true;
                    conditionMatched = !.match(matcheriseq);
                }
            } finally {
                // Reinstate region boundaries
                matcher.to = savedTo;
            }
            return conditionMatched && .match(matcheriseq);
        }
    }

    
For use with lookbehinds; matches the position where the lookbehind was encountered.
    static Node lookbehindEnd = new Node() {
        boolean match(Matcher matcherint iCharSequence seq) {
            return i == matcher.lookbehindTo;
        }
    };

    
Zero width positive lookbehind.
    static class Behind extends Node {
        Node cond;
        int rmaxrmin;
        Behind(Node condint rmaxint rmin) {
            this. = cond;
            this. = rmax;
            this. = rmin;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int savedFrom = matcher.from;
            boolean conditionMatched = false;
            int startIndex = (!matcher.transparentBounds) ?
                             matcher.from : 0;
            int from = Math.max(i - startIndex);
            // Set end boundary
            int savedLBT = matcher.lookbehindTo;
            matcher.lookbehindTo = i;
            // Relax transparent region boundaries for lookbehind
            if (matcher.transparentBounds)
                matcher.from = 0;
            for (int j = i - ; !conditionMatched && j >= fromj--) {
                conditionMatched = .match(matcherjseq);
            }
            matcher.from = savedFrom;
            matcher.lookbehindTo = savedLBT;
            return conditionMatched && .match(matcheriseq);
        }
    }

    
Zero width positive lookbehind, including supplementary characters or unpaired surrogates.
    static final class BehindS extends Behind {
        BehindS(Node condint rmaxint rmin) {
            super(condrmaxrmin);
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int rmaxChars = countChars(seqi, -);
            int rminChars = countChars(seqi, -);
            int savedFrom = matcher.from;
            int startIndex = (!matcher.transparentBounds) ?
                             matcher.from : 0;
            boolean conditionMatched = false;
            int from = Math.max(i - rmaxCharsstartIndex);
            // Set end boundary
            int savedLBT = matcher.lookbehindTo;
            matcher.lookbehindTo = i;
            // Relax transparent region boundaries for lookbehind
            if (matcher.transparentBounds)
                matcher.from = 0;
            for (int j = i - rminChars;
                 !conditionMatched && j >= from;
                 j -= j>from ? countChars(seqj, -1) : 1) {
                conditionMatched = .match(matcherjseq);
            }
            matcher.from = savedFrom;
            matcher.lookbehindTo = savedLBT;
            return conditionMatched && .match(matcheriseq);
        }
    }

    
Zero width negative lookbehind.
    static class NotBehind extends Node {
        Node cond;
        int rmaxrmin;
        NotBehind(Node condint rmaxint rmin) {
            this. = cond;
            this. = rmax;
            this. = rmin;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int savedLBT = matcher.lookbehindTo;
            int savedFrom = matcher.from;
            boolean conditionMatched = false;
            int startIndex = (!matcher.transparentBounds) ?
                             matcher.from : 0;
            int from = Math.max(i - startIndex);
            matcher.lookbehindTo = i;
            // Relax transparent region boundaries for lookbehind
            if (matcher.transparentBounds)
                matcher.from = 0;
            for (int j = i - ; !conditionMatched && j >= fromj--) {
                conditionMatched = .match(matcherjseq);
            }
            // Reinstate region boundaries
            matcher.from = savedFrom;
            matcher.lookbehindTo = savedLBT;
            return !conditionMatched && .match(matcheriseq);
        }
    }

    
Zero width negative lookbehind, including supplementary characters or unpaired surrogates.
    static final class NotBehindS extends NotBehind {
        NotBehindS(Node condint rmaxint rmin) {
            super(condrmaxrmin);
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int rmaxChars = countChars(seqi, -);
            int rminChars = countChars(seqi, -);
            int savedFrom = matcher.from;
            int savedLBT = matcher.lookbehindTo;
            boolean conditionMatched = false;
            int startIndex = (!matcher.transparentBounds) ?
                             matcher.from : 0;
            int from = Math.max(i - rmaxCharsstartIndex);
            matcher.lookbehindTo = i;
            // Relax transparent region boundaries for lookbehind
            if (matcher.transparentBounds)
                matcher.from = 0;
            for (int j = i - rminChars;
                 !conditionMatched && j >= from;
                 j -= j>from ? countChars(seqj, -1) : 1) {
                conditionMatched = .match(matcherjseq);
            }
            //Reinstate region boundaries
            matcher.from = savedFrom;
            matcher.lookbehindTo = savedLBT;
            return !conditionMatched && .match(matcheriseq);
        }
    }

    
Returns the set union of two CharProperty nodes.
    private static CharProperty union(final CharProperty lhs,
                                      final CharProperty rhs) {
        return new CharProperty() {
                boolean isSatisfiedBy(int ch) {
                    return lhs.isSatisfiedBy(ch) || rhs.isSatisfiedBy(ch);}};
    }

    
Returns the set intersection of two CharProperty nodes.
    private static CharProperty intersection(final CharProperty lhs,
                                             final CharProperty rhs) {
        return new CharProperty() {
                boolean isSatisfiedBy(int ch) {
                    return lhs.isSatisfiedBy(ch) && rhs.isSatisfiedBy(ch);}};
    }

    
Returns the set difference of two CharProperty nodes.
    private static CharProperty setDifference(final CharProperty lhs,
                                              final CharProperty rhs) {
        return new CharProperty() {
                boolean isSatisfiedBy(int ch) {
                    return ! rhs.isSatisfiedBy(ch) && lhs.isSatisfiedBy(ch);}};
    }

    
Handles word boundaries. Includes a field to allow this one class to deal with the different types of word boundaries we can match. The word characters include underscores, letters, and digits. Non spacing marks can are also part of a word if they have a base character, otherwise they are ignored for purposes of finding word boundaries.
    static final class Bound extends Node {
        static int LEFT = 0x1;
        static int RIGHT= 0x2;
        static int BOTH = 0x3;
        static int NONE = 0x4;
        int type;
        boolean useUWORD;
        Bound(int nboolean useUWORD) {
             = n;
            this. = useUWORD;
        }
        boolean isWord(int ch) {
            return  ? ..is(ch)
                            : (ch == '_' || Character.isLetterOrDigit(ch));
        }
        int check(Matcher matcherint iCharSequence seq) {
            int ch;
            boolean left = false;
            int startIndex = matcher.from;
            int endIndex = matcher.to;
            if (matcher.transparentBounds) {
                startIndex = 0;
                endIndex = matcher.getTextLength();
            }
            if (i > startIndex) {
                ch = Character.codePointBefore(seqi);
                left = (isWord(ch) ||
                    ((Character.getType(ch) == .)
                     && hasBaseCharacter(matcheri-1, seq)));
            }
            boolean right = false;
            if (i < endIndex) {
                ch = Character.codePointAt(seqi);
                right = (isWord(ch) ||
                    ((Character.getType(ch) == .)
                     && hasBaseCharacter(matcheriseq)));
            } else {
                // Tried to access char past the end
                matcher.hitEnd = true;
                // The addition of another char could wreck a boundary
                matcher.requireEnd = true;
            }
            return ((left ^ right) ? (right ?  : ) : );
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            return (check(matcheriseq) & ) > 0
                && .match(matcheriseq);
        }
    }

    
Non spacing marks only count as word characters in bounds calculations if they have a base character.
    private static boolean hasBaseCharacter(Matcher matcherint i,
                                            CharSequence seq)
    {
        int start = (!matcher.transparentBounds) ?
            matcher.from : 0;
        for (int x=ix >= startx--) {
            int ch = Character.codePointAt(seqx);
            if (Character.isLetterOrDigit(ch))
                return true;
            if (Character.getType(ch) == .)
                continue;
            return false;
        }
        return false;
    }

    
Attempts to match a slice in the input using the Boyer-Moore string matching algorithm. The algorithm is based on the idea that the pattern can be shifted farther ahead in the search text if it is matched right to left.

The pattern is compared to the input one character at a time, from the rightmost character in the pattern to the left. If the characters all match the pattern has been found. If a character does not match, the pattern is shifted right a distance that is the maximum of two functions, the bad character shift and the good suffix shift. This shift moves the attempted match position through the input more quickly than a naive one position at a time check.

The bad character shift is based on the character from the text that did not match. If the character does not appear in the pattern, the pattern can be shifted completely beyond the bad character. If the character does occur in the pattern, the pattern can be shifted to line the pattern up with the next occurrence of that character.

The good suffix shift is based on the idea that some subset on the right side of the pattern has matched. When a bad character is found, the pattern can be shifted right by the pattern length if the subset does not occur again in pattern, or by the amount of distance to the next occurrence of the subset in the pattern. Boyer-Moore search methods adapted from code by Amy Yu.

    static class BnM extends Node {
        int[] buffer;
        int[] lastOcc;
        int[] optoSft;

        
Pre calculates arrays needed to generate the bad character shift and the good suffix shift. Only the last seven bits are used to see if chars match; This keeps the tables small and covers the heavily used ASCII range, but occasionally results in an aliased match for the bad character shift.
        static Node optimize(Node node) {
            if (!(node instanceof Slice)) {
                return node;
            }
            int[] src = ((Slicenode).;
            int patternLength = src.length;
            // The BM algorithm requires a bit of overhead;
            // If the pattern is short don't use it, since
            // a shift larger than the pattern length cannot
            // be used anyway.
            if (patternLength < 4) {
                return node;
            }
            int ijk;
            int[] lastOcc = new int[128];
            int[] optoSft = new int[patternLength];
            // Precalculate part of the bad character shift
            // It is a table for where in the pattern each
            // lower 7-bit value occurs
            for (i = 0; i < patternLengthi++) {
                lastOcc[src[i]&0x7F] = i + 1;
            }
            // Precalculate the good suffix shift
            // i is the shift amount being considered
NEXT:       for (i = patternLengthi > 0; i--) {
                // j is the beginning index of suffix being considered
                for (j = patternLength - 1; j >= ij--) {
                    // Testing for good suffix
                    if (src[j] == src[j-i]) {
                        // src[j..len] is a good suffix
                        optoSft[j-1] = i;
                    } else {
                        // No match. The array has already been
                        // filled up with correct values before.
                        continue NEXT;
                    }
                }
                // This fills up the remaining of optoSft
                // any suffix can not have larger shift amount
                // then its sub-suffix. Why???
                while (j > 0) {
                    optoSft[--j] = i;
                }
            }
            // Set the guard value because of unicode compression
            optoSft[patternLength-1] = 1;
            if (node instanceof SliceS)
                return new BnMS(srclastOccoptoSftnode.next);
            return new BnM(srclastOccoptoSftnode.next);
        }
        BnM(int[] srcint[] lastOccint[] optoSftNode next) {
            this. = src;
            this. = lastOcc;
            this. = optoSft;
            this. = next;
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int[] src = ;
            int patternLength = src.length;
            int last = matcher.to - patternLength;
            // Loop over all possible match positions in text
NEXT:       while (i <= last) {
                // Loop over pattern from right to left
                for (int j = patternLength - 1; j >= 0; j--) {
                    int ch = seq.charAt(i+j);
                    if (ch != src[j]) {
                        // Shift search to the right by the maximum of the
                        // bad character shift and the good suffix shift
                        i += Math.max(j + 1 - [ch&0x7F], [j]);
                        continue NEXT;
                    }
                }
                // Entire pattern matched starting at i
                matcher.first = i;
                boolean ret = .match(matcheri + patternLengthseq);
                if (ret) {
                    matcher.first = i;
                    matcher.groups[0] = matcher.first;
                    matcher.groups[1] = matcher.last;
                    return true;
                }
                i++;
            }
            // BnM is only used as the leading node in the unanchored case,
            // and it replaced its Start() which always searches to the end
            // if it doesn't find what it's looking for, so hitEnd is true.
            matcher.hitEnd = true;
            return false;
        }
        boolean study(TreeInfo info) {
            info.minLength += .;
            info.maxValid = false;
            return .study(info);
        }
    }

    
Supplementary support version of BnM(). Unpaired surrogates are also handled by this class.
    static final class BnMS extends BnM {
        int lengthInChars;
        BnMS(int[] srcint[] lastOccint[] optoSftNode next) {
            super(srclastOccoptoSftnext);
            for (int x = 0; x < .x++) {
                 += Character.charCount([x]);
            }
        }
        boolean match(Matcher matcherint iCharSequence seq) {
            int[] src = ;
            int patternLength = src.length;
            int last = matcher.to - ;
            // Loop over all possible match positions in text
NEXT:       while (i <= last) {
                // Loop over pattern from right to left
                int ch;
                for (int j = countChars(seqipatternLength), x = patternLength - 1;
                     j > 0; j -= Character.charCount(ch), x--) {
                    ch = Character.codePointBefore(seqi+j);
                    if (ch != src[x]) {
                        // Shift search to the right by the maximum of the
                        // bad character shift and the good suffix shift
                        int n = Math.max(x + 1 - [ch&0x7F], [x]);
                        i += countChars(seqin);
                        continue NEXT;
                    }
                }
                // Entire pattern matched starting at i
                matcher.first = i;
                boolean ret = .match(matcheri + seq);
                if (ret) {
                    matcher.first = i;
                    matcher.groups[0] = matcher.first;
                    matcher.groups[1] = matcher.last;
                    return true;
                }
                i += countChars(seqi, 1);
            }
            matcher.hitEnd = true;
            return false;
        }
    }
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

    
This must be the very first initializer.
    static Node accept = new Node();
    static Node lastAccept = new LastNode();
    private static class CharPropertyNames {
        static CharProperty charPropertyFor(String name) {
            CharPropertyFactory m = .get(name);
            return m == null ? null : m.make();
        }
        private static abstract class CharPropertyFactory {
            abstract CharProperty make();
        }
        private static void defCategory(String name,
                                        final int typeMask) {
            .put(namenew CharPropertyFactory() {
                    CharProperty make() { return new Category(typeMask);}});
        }
        private static void defRange(String name,
                                     final int lowerfinal int upper) {
            .put(namenew CharPropertyFactory() {
                    CharProperty make() { return rangeFor(lowerupper);}});
        }
        private static void defCtype(String name,
                                     final int ctype) {
            .put(namenew CharPropertyFactory() {
                    CharProperty make() { return new Ctype(ctype);}});
        }
        private static abstract class CloneableProperty
            extends CharProperty implements Cloneable
        {
            public CloneableProperty clone() {
                try {
                    return (CloneablePropertysuper.clone();
                } catch (CloneNotSupportedException e) {
                    throw new AssertionError(e);
                }
            }
        }
        private static void defClone(String name,
                                     final CloneableProperty p) {
            .put(namenew CharPropertyFactory() {
                    CharProperty make() { return p.clone();}});
        }
        private static final HashMap<StringCharPropertyFactorymap
            = new HashMap<>();
        static {
            // Unicode character property aliases, defined in
            // http://www.unicode.org/Public/UNIDATA/PropertyValueAliases.txt
            defCategory("Cn", 1<<.);
            defCategory("Lu", 1<<.);
            defCategory("Ll", 1<<.);
            defCategory("Lt", 1<<.);
            defCategory("Lm", 1<<.);
            defCategory("Lo", 1<<.);
            defCategory("Mn", 1<<.);
            defCategory("Me", 1<<.);
            defCategory("Mc", 1<<.);
            defCategory("Nd", 1<<.);
            defCategory("Nl", 1<<.);
            defCategory("No", 1<<.);
            defCategory("Zs", 1<<.);
            defCategory("Zl", 1<<.);
            defCategory("Zp", 1<<.);
            defCategory("Cc", 1<<.);
            defCategory("Cf", 1<<.);
            defCategory("Co", 1<<.);
            defCategory("Cs", 1<<.);
            defCategory("Pd", 1<<.);
            defCategory("Ps", 1<<.);
            defCategory("Pe", 1<<.);
            defCategory("Pc", 1<<.);
            defCategory("Po", 1<<.);
            defCategory("Sm", 1<<.);
            defCategory("Sc", 1<<.);
            defCategory("Sk", 1<<.);
            defCategory("So", 1<<.);
            defCategory("Pi", 1<<.);
            defCategory("Pf", 1<<.);
            defCategory("L", ((1<<.) |
                              (1<<.) |
                              (1<<.) |
                              (1<<.)  |
                              (1<<.)));
            defCategory("M", ((1<<.) |
                              (1<<.)   |
                              (1<<.)));
            defCategory("N", ((1<<.) |
                              (1<<.)        |
                              (1<<.)));
            defCategory("Z", ((1<<.) |
                              (1<<.)  |
                              (1<<.)));
            defCategory("C", ((1<<.)     |
                              (1<<.)      |
                              (1<<.) |
                              (1<<.))); // Other
            defCategory("P", ((1<<.)      |
                              (1<<.)     |
                              (1<<.)       |
                              (1<<.) |
                              (1<<.)     |
                              (1<<.) |
                              (1<<.)));
            defCategory("S", ((1<<.)     |
                              (1<<.) |
                              (1<<.) |
                              (1<<.)));
            defCategory("LC", ((1<<.) |
                               (1<<.) |
                               (1<<.)));
            defCategory("LD", ((1<<.) |
                               (1<<.) |
                               (1<<.) |
                               (1<<.)  |
                               (1<<.)     |
                               (1<<.)));
            defRange("L1", 0x00, 0xFF); // Latin-1
            .put("all"new CharPropertyFactory() {
                    CharProperty make() { return new All(); }});
            // Posix regular expression character classes, defined in
            // http://www.unix.org/onlinepubs/009695399/basedefs/xbd_chap09.html
            defRange("ASCII", 0x00, 0x7F);   // ASCII
            defCtype("Alnum".);  // Alphanumeric characters
            defCtype("Alpha".);  // Alphabetic characters
            defCtype("Blank".);  // Space and tab characters
            defCtype("Cntrl".);  // Control characters
            defRange("Digit"'0''9');     // Numeric characters
            defCtype("Graph".);  // printable and visible
            defRange("Lower"'a''z');     // Lower-case alphabetic
            defRange("Print", 0x20, 0x7E);   // Printable characters
            defCtype("Punct".);  // Punctuation characters
            defCtype("Space".);  // Space characters
            defRange("Upper"'A''Z');     // Upper-case alphabetic
            defCtype("XDigit",.); // hexadecimal digits
            // Java character properties, defined by methods in Character.java
            defClone("javaLowerCase"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isLowerCase(ch);}});
            defClone("javaUpperCase"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isUpperCase(ch);}});
            defClone("javaAlphabetic"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isAlphabetic(ch);}});
            defClone("javaIdeographic"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isIdeographic(ch);}});
            defClone("javaTitleCase"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isTitleCase(ch);}});
            defClone("javaDigit"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isDigit(ch);}});
            defClone("javaDefined"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isDefined(ch);}});
            defClone("javaLetter"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isLetter(ch);}});
            defClone("javaLetterOrDigit"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isLetterOrDigit(ch);}});
            defClone("javaJavaIdentifierStart"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isJavaIdentifierStart(ch);}});
            defClone("javaJavaIdentifierPart"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isJavaIdentifierPart(ch);}});
            defClone("javaUnicodeIdentifierStart"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isUnicodeIdentifierStart(ch);}});
            defClone("javaUnicodeIdentifierPart"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isUnicodeIdentifierPart(ch);}});
            defClone("javaIdentifierIgnorable"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isIdentifierIgnorable(ch);}});
            defClone("javaSpaceChar"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isSpaceChar(ch);}});
            defClone("javaWhitespace"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isWhitespace(ch);}});
            defClone("javaISOControl"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isISOControl(ch);}});
            defClone("javaMirrored"new CloneableProperty() {
                boolean isSatisfiedBy(int ch) {
                    return Character.isMirrored(ch);}});
        }
    }
New to GrepCode? Check out our FAQ X