2 // This software is now distributed according to
3 // the Lesser Gnu Public License. Please see
4 // http://www.gnu.org/copyleft/lesser.txt for
8 package com.stevesoft.pat;
10 import jalview.util.MessageManager;
13 import java.io.FilenameFilter;
14 import java.util.BitSet;
15 import java.util.Hashtable;
17 import com.stevesoft.pat.wrap.StringWrap;
20 /** Matches a Unicode punctuation character. */
21 class UnicodePunct extends UniValidator
24 public int validate(StringLike s, int from, int to)
26 return from < s.length() && Prop.isPunct(s.charAt(from)) ? to : -1;
30 /** Matches a Unicode white space character. */
31 class UnicodeWhite extends UniValidator
34 public int validate(StringLike s, int from, int to)
36 return from < s.length() && Prop.isWhite(s.charAt(from)) ? to : -1;
41 * Matches a character that is not a Unicode punctuation character.
43 class NUnicodePunct extends UniValidator
46 public int validate(StringLike s, int from, int to)
48 return from < s.length() && !Prop.isPunct(s.charAt(from)) ? to : -1;
53 * Matches a character that is not a Unicode white space character.
55 class NUnicodeWhite extends UniValidator
58 public int validate(StringLike s, int from, int to)
60 return from < s.length() && !Prop.isWhite(s.charAt(from)) ? to : -1;
64 /** Matches a Unicode word character: an alphanumeric or underscore. */
65 class UnicodeW extends UniValidator
68 public int validate(StringLike s, int from, int to)
70 if (from >= s.length())
74 char c = s.charAt(from);
75 return (Prop.isAlphabetic(c) || Prop.isDecimalDigit(c) || c == '_') ? to
80 /** Matches a character that is not a Unicode alphanumeric or underscore. */
81 class NUnicodeW extends UniValidator
84 public int validate(StringLike s, int from, int to)
86 if (from >= s.length())
90 char c = s.charAt(from);
91 return !(Prop.isAlphabetic(c) || Prop.isDecimalDigit(c) || c == '_') ? to
96 /** Matches a Unicode decimal digit. */
97 class UnicodeDigit extends UniValidator
100 public int validate(StringLike s, int from, int to)
102 return from < s.length() && Prop.isDecimalDigit(s.charAt(from)) ? to
107 /** Matches a character that is not a Unicode digit. */
108 class NUnicodeDigit extends UniValidator
111 public int validate(StringLike s, int from, int to)
113 return from < s.length() && !Prop.isDecimalDigit(s.charAt(from)) ? to
118 /** Matches a Unicode math character. */
119 class UnicodeMath extends UniValidator
122 public int validate(StringLike s, int from, int to)
124 return from < s.length() && Prop.isMath(s.charAt(from)) ? to : -1;
128 /** Matches a non-math Unicode character. */
129 class NUnicodeMath extends UniValidator
132 public int validate(StringLike s, int from, int to)
134 return from < s.length() && !Prop.isMath(s.charAt(from)) ? to : -1;
138 /** Matches a Unicode currency symbol. */
139 class UnicodeCurrency extends UniValidator
142 public int validate(StringLike s, int from, int to)
144 return from < s.length() && Prop.isCurrency(s.charAt(from)) ? to : -1;
148 /** Matches a non-currency symbol Unicode character. */
149 class NUnicodeCurrency extends UniValidator
152 public int validate(StringLike s, int from, int to)
154 return from < s.length() && !Prop.isCurrency(s.charAt(from)) ? to : -1;
158 /** Matches a Unicode alphabetic character. */
159 class UnicodeAlpha extends UniValidator
162 public int validate(StringLike s, int from, int to)
164 return from < s.length() && Prop.isAlphabetic(s.charAt(from)) ? to : -1;
168 /** Matches a non-alphabetic Unicode character. */
169 class NUnicodeAlpha extends UniValidator
172 public int validate(StringLike s, int from, int to)
174 return from < s.length() && !Prop.isAlphabetic(s.charAt(from)) ? to
179 /** Matches an upper case Unicode character. */
180 class UnicodeUpper extends UniValidator
183 public int validate(StringLike s, int from, int to)
185 return from < s.length() && isUpper(s.charAt(from)) ? to : -1;
188 final boolean isUpper(char c)
190 return c == CaseMgr.toUpperCase(c) && c != CaseMgr.toLowerCase(c);
194 /** Matches an upper case Unicode character. */
195 class UnicodeLower extends UniValidator
198 public int validate(StringLike s, int from, int to)
200 return from < s.length() && isLower(s.charAt(from)) ? to : -1;
203 final boolean isLower(char c)
205 return c != CaseMgr.toUpperCase(c) && c == CaseMgr.toLowerCase(c);
210 * Regex provides the parser which constructs the linked list of Pattern classes
213 * For the purpose of this documentation, the fact that java interprets the
214 * backslash will be ignored. In practice, however, you will need a double
215 * backslash to obtain a string that contains a single backslash character.
216 * Thus, the example pattern "\b" should really be typed as "\\b" inside java
219 * Note that Regex is part of package "com.stevesoft.pat". To use it, simply
220 * import com.stevesoft.pat.Regex at the top of your file.
222 * Regex is made with a constructor that takes a String that defines the regular
223 * expression. Thus, for example
226 * Regex r = new Regex("[a-c]*");
229 * matches any number of characters so long as the are 'a', 'b', or 'c').
231 * To attempt to match the Pattern to a given string, you can use either the
232 * search(String) member function, or the matchAt(String,int position) member
233 * function. These functions return a boolean which tells you whether or not the
234 * thing worked, and sets the methods "charsMatched()" and "matchedFrom()" in
235 * the Regex object appropriately.
237 * The portion of the string before the match can be obtained by the left()
238 * member, and the portion after the match can be obtained by the right()
241 * Essentially, this package implements a syntax that is very much like the perl
242 * 5 regular expression syntax.
247 * Regex r = new Regex("x(a|b)y");
248 * r.matchAt("xay", 0);
249 * System.out.println("sub = " + r.stringMatched(1));
252 * The above would print "sub = a".
255 * r.left() // would return "x"
256 * r.right() // would return "y"
260 * Differences between this package and perl5:<br>
261 * The extended Pattern for setting flags, is now supported, but the flags are
262 * different. "(?i)" tells the pattern to ignore case, "(?Q)" sets the
263 * "dontMatchInQuotes" flag, and "(?iQ)" sets them both. You can change the
264 * escape character. The pattern
276 * , but note that the sequence
282 * <b>must</b> occur at the very beginning of the pattern. There may be other
283 * small differences as well. I will either make my package conform or note them
284 * as I become aware of them.
286 * This package supports additional patterns not in perl5: <center>
291 * <td>This matches all characters between the '(' character and the balancing
292 * ')' character. Thus, it will match "()" as well as "(())". The balancing
293 * characters are arbitrary, thus (?@{}) matches on "{}" and "{{}}".</td>
297 * <td>Moves the pointer backwards within the text. This allows you to make a
298 * "look behind." It fails if it attempts to move to a position before the
299 * beginning of the string. "x(?<1)" is equivalent to "(?=x)". The number, 1
300 * in this example, is the number of characters to move backwards.</td>
304 * @author Steven R. Brandt
305 * @version package com.stevesoft.pat, release 1.5.3
308 public class Regex extends RegRes implements FilenameFilter
316 * swingjs.JSUtil.loadStaticResource$S("core/core_stevesoft.z.js");
321 * BackRefOffset gives the identity number of the first pattern. Version 1.0
322 * used zero, version 1.1 uses 1 to be more compatible with perl.
324 static int BackRefOffset = 1;
326 private static Pattern none = new NoPattern();
328 Pattern thePattern = none;
330 patInt minMatch = new patInt(0);
332 static Hashtable validators = new Hashtable();
335 define("p", "(?>1)", new UnicodePunct());
336 define("P", "(?>1)", new NUnicodePunct());
337 define("s", "(?>1)", new UnicodeWhite());
338 define("S", "(?>1)", new NUnicodeWhite());
339 define("w", "(?>1)", new UnicodeW());
340 define("W", "(?>1)", new NUnicodeW());
341 define("d", "(?>1)", new UnicodeDigit());
342 define("D", "(?>1)", new NUnicodeDigit());
343 define("m", "(?>1)", new UnicodeMath());
344 define("M", "(?>1)", new NUnicodeMath());
345 define("c", "(?>1)", new UnicodeCurrency());
346 define("C", "(?>1)", new NUnicodeCurrency());
347 define("a", "(?>1)", new UnicodeAlpha());
348 define("A", "(?>1)", new NUnicodeAlpha());
349 define("uc", "(?>1)", new UnicodeUpper());
350 define("lc", "(?>1)", new UnicodeLower());
353 /** Set the dontMatch in quotes flag. */
354 public void setDontMatchInQuotes(boolean b)
356 dontMatchInQuotes = b;
359 /** Find out if the dontMatchInQuotes flag is enabled. */
360 public boolean getDontMatchInQuotes()
362 return dontMatchInQuotes;
365 boolean dontMatchInQuotes = false;
368 * Set the state of the ignoreCase flag. If set to true, then the pattern
369 * matcher will ignore case when searching for a match.
371 public void setIgnoreCase(boolean b)
377 * Get the state of the ignoreCase flag. Returns true if we are ignoring the
378 * case of the pattern, false otherwise.
380 public boolean getIgnoreCase()
385 boolean ignoreCase = false;
387 static boolean defaultMFlag = false;
390 * Set the default value of the m flag. If it is set to true, then the MFlag
391 * will be on for any regex search executed.
393 public static void setDefaultMFlag(boolean mFlag)
395 defaultMFlag = mFlag;
399 * Get the default value of the m flag. If it is set to true, then the MFlag
400 * will be on for any regex search executed.
402 public static boolean getDefaultMFlag()
408 * Initializes the object without a Pattern. To supply a Pattern use
411 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
418 * Create and compile a Regex, but do not throw any exceptions. If you wish to
419 * have exceptions thrown for syntax errors, you must use the Regex(void)
420 * constructor to create the Regex object, and then call the compile method.
421 * Therefore, you should only call this method when you know your pattern is
422 * right. I will probably become more like
424 * @see com.stevesoft.pat.Regex#search(java.lang.String)
425 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
427 public Regex(String s)
432 } catch (RegSyntax rs)
437 ReplaceRule rep = null;
440 * Create and compile both a Regex and a ReplaceRule.
442 * @see com.stevesoft.pat.ReplaceRule
443 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
445 public Regex(String s, String rp)
448 rep = ReplaceRule.perlCode(rp);
452 * Create and compile a Regex, but give it the ReplaceRule specified. This
453 * allows the user finer control of the Replacement process, if that is
456 * @see com.stevesoft.pat.ReplaceRule
457 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
459 public Regex(String s, ReplaceRule rp)
466 * Change the ReplaceRule of this Regex by compiling a new one using String
469 public void setReplaceRule(String rp)
471 rep = ReplaceRule.perlCode(rp);
472 repr = null; // Clear Replacer history
475 /** Change the ReplaceRule of this Regex to rp. */
476 public void setReplaceRule(ReplaceRule rp)
482 * Test to see if a custom defined rule exists.
484 * @see com.stevesoft.pat#define(java.lang.String,java.lang.String,Validator)
486 public static boolean isDefined(String nm)
488 return validators.get(nm) != null;
492 * Removes a custom defined rule.
494 * @see com.stevesoft.pat#define(java.lang.String,java.lang.String,Validator)
496 public static void undefine(String nm)
498 validators.remove(nm);
502 * Defines a method to create a new rule. See test/deriv2.java and
503 * test/deriv3.java for examples of how to use it.
505 public static void define(String nm, String pat, Validator v)
508 validators.put(nm, v);
512 * Defines a shorthand for a pattern. The pattern will be invoked by a string
513 * that has the form "(??"+nm+")".
515 public static void define(String nm, String pat)
517 validators.put(nm, pat);
520 /** Get the current ReplaceRule. */
521 public ReplaceRule getReplaceRule()
526 Replacer repr = null;
528 final Replacer _getReplacer()
530 return repr == null ? repr = new Replacer() : repr;
533 public Replacer getReplacer()
537 repr = new Replacer();
545 * Replace the first occurence of this pattern in String s according to the
548 * @see com.stevesoft.pat.ReplaceRule
549 * @see com.stevesoft.pat.Regex#getReplaceRule()
551 public String replaceFirst(String s)
553 return _getReplacer().replaceFirstRegion(s, this, 0, s.length())
558 * Replace the first occurence of this pattern in String s beginning with
559 * position pos according to the ReplaceRule.
561 * @see com.stevesoft.pat.ReplaceRule
562 * @see com.stevesoft.pat.Regex#getReplaceRule()
564 public String replaceFirstFrom(String s, int pos)
566 return _getReplacer().replaceFirstRegion(s, this, pos, s.length())
571 * Replace the first occurence of this pattern in String s beginning with
572 * position start and ending with end according to the ReplaceRule.
574 * @see com.stevesoft.pat.ReplaceRule
575 * @see com.stevesoft.pat.Regex#getReplaceRule()
577 public String replaceFirstRegion(String s, int start, int end)
579 return _getReplacer().replaceFirstRegion(s, this, start, end)
584 * Replace all occurences of this pattern in String s according to the
587 * @see com.stevesoft.pat.ReplaceRule
588 * @see com.stevesoft.pat.Regex#getReplaceRule()
590 public String replaceAll(String s)
592 return _getReplacer().replaceAllRegion(s, this, 0, s.length())
596 public StringLike replaceAll(StringLike s)
598 return _getReplacer().replaceAllRegion(s, this, 0, s.length());
602 * Replace all occurences of this pattern in String s beginning with position
603 * pos according to the ReplaceRule.
605 * @see com.stevesoft.pat.ReplaceRule
606 * @see com.stevesoft.pat.Regex#getReplaceRule()
608 public String replaceAllFrom(String s, int pos)
610 return _getReplacer().replaceAllRegion(s, this, pos, s.length())
615 * Replace all occurences of this pattern in String s beginning with position
616 * start and ending with end according to the ReplaceRule.
618 * @see com.stevesoft.pat.ReplaceRule
619 * @see com.stevesoft.pat.Regex#getReplaceRule()
621 public String replaceAllRegion(String s, int start, int end)
623 return _getReplacer().replaceAllRegion(s, this, start, end).toString();
626 /** Essentially clones the Regex object */
627 public Regex(Regex r)
630 dontMatchInQuotes = r.dontMatchInQuotes;
632 ignoreCase = r.ignoreCase;
640 rep = (ReplaceRule) r.rep.clone();
643 * try { compile(r.toString()); } catch(RegSyntax r_) {}
645 thePattern = r.thePattern.clone(new Hashtable());
646 minMatch = r.minMatch;
651 * By default, the escape character is the backslash, but you can make it
652 * anything you want by setting this variable.
654 public char esc = Pattern.ESC;
657 * This method compiles a regular expression, making it possible to call the
658 * search or matchAt methods.
660 * @exception com.stevesoft.pat.RegSyntax
661 * is thrown if a syntax error is encountered in the pattern. For
662 * example, "x{3,1}" or "*a" are not valid patterns.
663 * @see com.stevesoft.pat.Regex#search
664 * @see com.stevesoft.pat.Regex#matchAt
666 public void compile(String prepat) throws RegSyntax
668 String postpat = parsePerl.codify(prepat, true);
669 String pat = postpat == null ? prepat : postpat;
672 dontMatchInQuotes = false;
673 Rthings mk = new Rthings(this);
679 minMatch = new patInt(0);
680 StrPos sp = new StrPos(pat, 0);
681 if (sp.incMatch("(?e="))
687 newpat = reEscape(pat.substring(6), newEsc, Pattern.ESC);
690 else if (esc != Pattern.ESC)
692 newpat = reEscape(pat, esc, Pattern.ESC);
694 thePattern = _compile(newpat, mk);
695 numSubs_ = mk.val - offset;
700 * If a Regex is compared against a Regex, a check is done to see that the
701 * patterns are equal as well as the most recent match. If a Regex is compare
702 * with a RegRes, only the result of the most recent match is compared.
705 public boolean equals(Object o)
707 if (o instanceof Regex)
709 if (toString().equals(o.toString()))
711 return super.equals(o);
720 return super.equals(o);
724 /** A clone by any other name would smell as sweet. */
726 public Object clone()
728 return new Regex(this);
731 /** Return a clone of the underlying RegRes object. */
732 public RegRes result()
734 return (RegRes) super.clone();
737 // prep sets global variables of class
738 // Pattern so that it can access them
739 // during an attempt at a match
740 Pthings pt = new Pthings();
742 final Pthings prep(StringLike s)
745 pt.lastPos = matchedTo();
750 if ((s == null ? null : s.unwrap()) != (src == null ? null : s.unwrap()))
755 pt.dotDoesntMatchCR = dotDoesntMatchCR && (!sFlag);
756 pt.mFlag = (mFlag | defaultMFlag);
757 pt.ignoreCase = ignoreCase;
759 if (pt.marks != null)
761 for (int i = 0; i < pt.marks.length; i++)
767 pt.nMarks = numSubs_;
769 if (dontMatchInQuotes)
781 * Attempt to match a Pattern beginning at a specified location within the
784 * @see com.stevesoft.pat.Regex#search
786 public boolean matchAt(String s, int start_pos)
788 return _search(s, start_pos, start_pos);
792 * Attempt to match a Pattern beginning at a specified location within the
795 * @see com.stevesoft.pat.Regex#search
797 public boolean matchAt(StringLike s, int start_pos)
799 return _search(s, start_pos, start_pos);
803 * Search through a String for the first occurrence of a match.
805 * @see com.stevesoft.pat.Regex#searchFrom
806 * @see com.stevesoft.pat.Regex#matchAt
808 public boolean search(String s)
812 throw new NullPointerException(
814 .getString("exception.null_string_given_to_regex_search"));
816 return _search(s, 0, s.length());
819 public boolean search(StringLike sl)
823 throw new NullPointerException(
825 .getString("exception.null_string_like_given_to_regex_search"));
827 return _search(sl, 0, sl.length());
830 public boolean reverseSearch(String s)
834 throw new NullPointerException(
836 .getString("exception.null_string_given_to_regex_reverse_search"));
838 return _reverseSearch(s, 0, s.length());
841 public boolean reverseSearch(StringLike sl)
845 throw new NullPointerException(
847 .getString("exception.null_string_like_given_to_regex_reverse_search"));
849 return _reverseSearch(sl, 0, sl.length());
853 * Search through a String for the first occurence of a match, but start at
860 public boolean searchFrom(String s, int start)
864 throw new NullPointerException(
866 .getString("exception.null_string_like_given_to_regex_search_from"));
868 return _search(s, start, s.length());
871 public boolean searchFrom(StringLike s, int start)
875 throw new NullPointerException(
877 .getString("exception.null_string_like_given_to_regex_search_from"));
879 return _search(s, start, s.length());
883 * Search through a region of a String for the first occurence of a match.
885 public boolean searchRegion(String s, int start, int end)
889 throw new NullPointerException(
891 .getString("exception.null_string_like_given_to_regex_search_region"));
893 return _search(s, start, end);
897 * Set this to change the default behavior of the "." pattern. By default it
898 * now matches perl's behavior and fails to match the '\n' character.
900 public static boolean dotDoesntMatchCR = true;
906 boolean gFlag = false;
908 /** Set the 'g' flag */
909 public void setGFlag(boolean b)
914 /** Get the state of the 'g' flag. */
915 public boolean getGFlag()
920 boolean sFlag = false;
922 /** Get the state of the sFlag */
923 public boolean getSFlag()
928 boolean mFlag = false;
930 /** Get the state of the sFlag */
931 public boolean getMFlag()
936 final boolean _search(String s, int start, int end)
938 return _search(new StringWrap(s), start, end);
941 final boolean _search(StringLike s, int start, int end)
943 if (gFlag && gFlagto > 0 && gFlags != null
944 && s.unwrap() == gFlags.unwrap())
950 Pthings pt = prep(s);
952 int up = (minMatch == null ? end : end - minMatch.i);
954 if (up < start && end >= start)
961 for (int i = start; i <= up; i++)
963 charsMatched_ = thePattern.matchAt(s, i, pt);
964 if (charsMatched_ >= 0)
966 matchFrom_ = thePattern.mfrom;
968 gFlagto = matchFrom_ + charsMatched_;
970 return didMatch_ = true;
977 for (int i = start; i <= up; i++)
979 i = skipper.find(src, i, up);
982 charsMatched_ = matchFrom_ = -1;
983 return didMatch_ = false;
985 charsMatched_ = thePattern.matchAt(s, i, pt);
986 if (charsMatched_ >= 0)
988 matchFrom_ = thePattern.mfrom;
990 gFlagto = matchFrom_ + charsMatched_;
992 return didMatch_ = true;
996 return didMatch_ = false;
1000 * final boolean _search(LongStringLike s,long start,long end) { if(gFlag &&
1001 * gFlagto > 0 && s==gFlags) start = gFlagto; gFlags = null;
1003 * Pthings pt=prep(s);
1005 * int up = end;//(minMatch == null ? end : end-minMatch.i);
1007 * if(up < start && end >= start) up = start;
1009 * if(skipper == null) { for(long i=start;i<=up;i++) { charsMatched_ =
1010 * thePattern.matchAt(s,i,pt); if(charsMatched_ >= 0) { matchFrom_ =
1011 * thePattern.mfrom; marks = pt.marks; gFlagto = matchFrom_+charsMatched_;
1012 * return didMatch_=true; } } } else { pt.no_check = true; for(long
1013 * i=start;i<=up;i++) { i = skipper.find(src,i,up); if(i<0) { charsMatched_ =
1014 * matchFrom_ = -1; return didMatch_ = false; } charsMatched_ =
1015 * thePattern.matchAt(s,i,pt); if(charsMatched_ >= 0) { matchFrom_ =
1016 * thePattern.mfrom; marks = pt.marks; gFlagto = matchFrom_+charsMatched_;
1017 * gFlags = s; return didMatch_=true; } else { i = s.adjustIndex(i); up =
1018 * s.adjustEnd(i); } } } return didMatch_=false; }
1021 boolean _reverseSearch(String s, int start, int end)
1023 return _reverseSearch(new StringWrap(s), start, end);
1026 boolean _reverseSearch(StringLike s, int start, int end)
1028 if (gFlag && gFlagto > 0 && s.unwrap() == gFlags.unwrap())
1033 Pthings pt = prep(s);
1034 for (int i = end; i >= start; i--)
1036 charsMatched_ = thePattern.matchAt(s, i, pt);
1037 if (charsMatched_ >= 0)
1039 matchFrom_ = thePattern.mfrom;
1041 gFlagto = matchFrom_ - 1;
1043 return didMatch_ = true;
1046 return didMatch_ = false;
1049 // This routine sets the cbits variable
1050 // of class Pattern. Cbits is true for
1051 // the bit corresponding to a character inside
1053 static StringLike lasts = null;
1055 static BitSet lastbs = null;
1057 static void setCbits(StringLike s, Pthings pt)
1064 BitSet bs = new BitSet(s.length());
1066 boolean setBit = false;
1067 for (int i = 0; i < s.length(); i++)
1073 char c = s.charAt(i);
1074 if (!setBit && c == '"')
1080 else if (!setBit && c == '\'')
1086 else if (setBit && c == qc)
1090 else if (setBit && c == '\\' && i + 1 < s.length())
1099 pt.cbits = lastbs = bs;
1103 // Wanted user to over-ride this in alpha version,
1104 // but it wasn't really necessary because of this trick:
1109 return getClass().newInstance();
1110 } catch (InstantiationException ie)
1113 } catch (IllegalAccessException iae)
1120 * Only needed for creating your own extensions of Regex. This method adds the
1121 * next Pattern in the chain of patterns or sets the Pattern if it is the
1124 protected void add(Pattern p2)
1138 * You only need to use this method if you are creating your own extentions to
1139 * Regex. compile1 compiles one Pattern element, it can be over-ridden to
1140 * allow the Regex compiler to understand new syntax. See deriv.java for an
1141 * example. This routine is the heart of class Regex. Rthings has one integer
1142 * member called intValue, it is used to keep track of the number of ()'s in
1145 * @exception com.stevesoft.pat.RegSyntax
1146 * is thrown when a nonsensensical pattern is supplied. For
1147 * example, a pattern beginning with *.
1149 protected void compile1(StrPos sp, Rthings mk) throws RegSyntax
1154 add(matchBracket(sp));
1156 else if (sp.match('|'))
1164 p = new NullPattern();
1169 else if (sp.incMatch("(?<"))
1171 patInt i = sp.getPatInt();
1174 RegSyntaxError.endItAll("No int after (?<");
1176 add(new Backup(i.intValue()));
1179 RegSyntaxError.endItAll("No ) after (?<");
1182 else if (sp.incMatch("(?>"))
1184 patInt i = sp.getPatInt();
1187 RegSyntaxError.endItAll("No int after (?>");
1189 add(new Backup(-i.intValue()));
1192 RegSyntaxError.endItAll("No ) after (?<");
1195 else if (sp.incMatch("(?@"))
1203 RegSyntaxError.endItAll("(?@ does not have closing paren");
1205 add(new Group(op, cl));
1207 else if (sp.incMatch("(?#"))
1209 while (!sp.match(')'))
1214 else if (sp.dontMatch && sp.c == 'w')
1216 // Regex r = new Regex();
1217 // r._compile("[a-zA-Z0-9_]",mk);
1218 // add(new Goop("\\w",r.thePattern));
1219 Bracket b = new Bracket(false);
1220 b.addOr(new Range('a', 'z'));
1221 b.addOr(new Range('A', 'Z'));
1222 b.addOr(new Range('0', '9'));
1223 b.addOr(new oneChar('_'));
1226 else if (sp.dontMatch && sp.c == 'G')
1230 else if (sp.dontMatch && sp.c == 's')
1232 // Regex r = new Regex();
1233 // r._compile("[ \t\n\r\b]",mk);
1234 // add(new Goop("\\s",r.thePattern));
1235 Bracket b = new Bracket(false);
1236 b.addOr(new oneChar((char) 32));
1237 b.addOr(new Range((char) 8, (char) 10));
1238 b.addOr(new oneChar((char) 13));
1241 else if (sp.dontMatch && sp.c == 'd')
1243 // Regex r = new Regex();
1244 // r._compile("[0-9]",mk);
1245 // add(new Goop("\\d",r.thePattern));
1246 Range digit = new Range('0', '9');
1247 digit.printBrackets = true;
1250 else if (sp.dontMatch && sp.c == 'W')
1252 // Regex r = new Regex();
1253 // r._compile("[^a-zA-Z0-9_]",mk);
1254 // add(new Goop("\\W",r.thePattern));
1255 Bracket b = new Bracket(true);
1256 b.addOr(new Range('a', 'z'));
1257 b.addOr(new Range('A', 'Z'));
1258 b.addOr(new Range('0', '9'));
1259 b.addOr(new oneChar('_'));
1262 else if (sp.dontMatch && sp.c == 'S')
1264 // Regex r = new Regex();
1265 // r._compile("[^ \t\n\r\b]",mk);
1266 // add(new Goop("\\S",r.thePattern));
1267 Bracket b = new Bracket(true);
1268 b.addOr(new oneChar((char) 32));
1269 b.addOr(new Range((char) 8, (char) 10));
1270 b.addOr(new oneChar((char) 13));
1273 else if (sp.dontMatch && sp.c == 'D')
1275 // Regex r = new Regex();
1276 // r._compile("[^0-9]",mk);
1277 // add(new Goop("\\D",r.thePattern));
1278 Bracket b = new Bracket(true);
1279 b.addOr(new Range('0', '9'));
1282 else if (sp.dontMatch && sp.c == 'B')
1284 Regex r = new Regex();
1285 r._compile("(?!" + back_slash + "b)", mk);
1288 else if (isOctalString(sp))
1292 d = 8 * d + sp.c - '0';
1293 StrPos sp2 = new StrPos(sp);
1295 if (isOctalDigit(sp2, false))
1298 d = 8 * d + sp.c - '0';
1300 add(new oneChar((char) d));
1302 else if (sp.dontMatch && sp.c >= '1' && sp.c <= '9')
1304 int iv = sp.c - '0';
1305 StrPos s2 = new StrPos(sp);
1307 if (!s2.dontMatch && s2.c >= '0' && s2.c <= '9')
1309 iv = 10 * iv + (s2.c - '0');
1312 add(new BackMatch(iv));
1314 else if (sp.dontMatch && sp.c == 'b')
1316 add(new Boundary());
1318 else if (sp.match('\b'))
1320 add(new Boundary());
1322 else if (sp.match('$'))
1326 else if (sp.dontMatch && sp.c == 'Z')
1328 add(new End(false));
1330 else if (sp.match('.'))
1334 else if (sp.incMatch("(??"))
1336 StringBuffer sb = new StringBuffer();
1337 StringBuffer sb2 = new StringBuffer();
1338 while (!sp.match(')') && !sp.match(':'))
1343 if (sp.incMatch(":"))
1345 while (!sp.match(')'))
1351 String sbs = sb.toString();
1352 if (validators.get(sbs) instanceof String)
1354 String pat = (String) validators.get(sbs);
1355 Regex r = newRegex();
1356 Rthings rth = new Rthings(this);
1357 rth.noBackRefs = true;
1358 r._compile(pat, rth);
1363 Custom cm = new Custom(sb.toString());
1366 Validator v2 = cm.v.arg(sb2.toString());
1369 v2.argsave = sb2.toString();
1370 String p = cm.v.pattern;
1374 Regex r = newRegex();
1375 Rthings rth = new Rthings(this);
1376 rth.noBackRefs = true;
1377 r._compile(cm.v.pattern, rth);
1378 cm.sub = r.thePattern;
1379 cm.sub.add(new CustomEndpoint(cm));
1380 cm.sub.setParent(cm);
1385 else if (sp.match('('))
1388 Regex r = newRegex();
1391 if (sp.incMatch("?:"))
1395 else if (sp.incMatch("?="))
1397 r.or = new lookAhead(false);
1399 else if (sp.incMatch("?!"))
1401 r.or = new lookAhead(true);
1403 else if (sp.match('?'))
1410 mk.ignoreCase = true;
1414 mk.dontMatchInQuotes = true;
1418 mk.optimizeMe = true;
1433 } while (!sp.match(')') && !sp.eos);
1436 if (sp.eos) // throw new RegSyntax
1438 RegSyntaxError.endItAll("Unclosed ()");
1442 { // just ordinary parenthesis
1443 r.or = mk.noBackRefs ? new Or() : new OrMark(mk.val++);
1447 add(r._compile(sp, mk));
1450 else if (sp.match('^'))
1452 add(new Start(true));
1454 else if (sp.dontMatch && sp.c == 'A')
1456 add(new Start(false));
1458 else if (sp.match('*'))
1460 addMulti(new patInt(0), new patInf());
1462 else if (sp.match('+'))
1464 addMulti(new patInt(1), new patInf());
1466 else if (sp.match('?'))
1468 addMulti(new patInt(0), new patInt(1));
1470 else if (sp.match('{'))
1472 boolean bad = false;
1473 StrPos sp2 = new StrPos(sp);
1474 // StringBuffer sb = new StringBuffer();
1476 patInt i1 = sp.getPatInt();
1487 * RegSyntaxError.endItAll( "String \"{"+i2+ "\" should be followed
1499 i2 = sp.getPatInt();
1502 if (i1 == null || i2 == null)
1505 * throw new RegSyntax("Badly formatted Multi: " +"{"+i1+","+i2+"}");
1512 add(new oneChar(sp.c));
1519 else if (sp.escMatch('x') && next2Hex(sp))
1522 int d = getHexDigit(sp);
1524 d = 16 * d + getHexDigit(sp);
1525 add(new oneChar((char) d));
1527 else if (sp.escMatch('c'))
1530 if (sp.c < Ctrl.cmap.length)
1532 add(new oneChar(Ctrl.cmap[sp.c]));
1536 add(new oneChar(sp.c));
1539 else if (sp.escMatch('f'))
1541 add(new oneChar((char) 12));
1543 else if (sp.escMatch('a'))
1545 add(new oneChar((char) 7));
1547 else if (sp.escMatch('t'))
1549 add(new oneChar('\t'));
1551 else if (sp.escMatch('n'))
1553 add(new oneChar('\n'));
1555 else if (sp.escMatch('r'))
1557 add(new oneChar('\r'));
1559 else if (sp.escMatch('b'))
1561 add(new oneChar('\b'));
1563 else if (sp.escMatch('e'))
1565 add(new oneChar((char) 27));
1569 add(new oneChar(sp.c));
1572 RegSyntaxError.endItAll("Unmatched right paren in pattern");
1577 // compiles all Pattern elements, internal method
1578 private Pattern _compile(String pat, Rthings mk) throws RegSyntax
1581 sFlag = mFlag = ignoreCase = gFlag = false;
1582 StrPos sp = new StrPos(pat, 0);
1583 thePattern = _compile(sp, mk);
1592 Pattern _compile(StrPos sp, Rthings mk) throws RegSyntax
1594 while (!(sp.eos || (or != null && sp.match(')'))))
1603 else if (sp.eos && mk.parenLevel != 0)
1605 RegSyntaxError.endItAll("Unclosed Parenthesis! lvl=" + mk.parenLevel);
1611 p = new NullPattern();
1616 return p == null ? new NullPattern() : p;
1619 // add a multi object to the end of the chain
1620 // which applies to the last object
1621 void addMulti(patInt i1, patInt i2) throws RegSyntax
1623 Pattern last, last2;
1624 for (last = p; last != null && last.next != null; last = last.next)
1628 if (last == null || last == p)
1634 for (last2 = p; last2.next != last; last2 = last2.next)
1639 if (last instanceof Multi && i1.intValue() == 0 && i2.intValue() == 1)
1641 ((Multi) last).matchFewest = true;
1643 else if (last instanceof FastMulti && i1.intValue() == 0
1644 && i2.intValue() == 1)
1646 ((FastMulti) last).matchFewest = true;
1648 else if (last instanceof DotMulti && i1.intValue() == 0
1649 && i2.intValue() == 1)
1651 ((DotMulti) last).matchFewest = true;
1653 else if (last instanceof Multi || last instanceof DotMulti
1654 || last instanceof FastMulti)
1656 throw new RegSyntax("Syntax error.");
1658 else if (last2 == null)
1660 p = mkMulti(i1, i2, p);
1664 last2.next = mkMulti(i1, i2, last);
1668 final static Pattern mkMulti(patInt lo, patInt hi, Pattern p)
1671 if (p instanceof Any && p.next == null)
1673 return new DotMulti(lo, hi);
1675 return RegOpt.safe4fm(p) ? (Pattern) new FastMulti(lo, hi, p)
1676 : (Pattern) new Multi(lo, hi, p);
1679 // process the bracket operator
1680 Pattern matchBracket(StrPos sp) throws RegSyntax
1685 ret = new Bracket(true);
1690 ret = new Bracket(false);
1694 // throw new RegSyntax
1695 RegSyntaxError.endItAll("Unmatched []");
1698 while (!sp.eos && !sp.match(']'))
1700 StrPos s1 = new StrPos(sp);
1702 StrPos s1_ = new StrPos(s1);
1704 if (s1.match('-') && !s1_.match(']'))
1706 StrPos s2 = new StrPos(s1);
1710 ret.addOr(new Range(sp.c, s2.c));
1715 else if (sp.escMatch('Q'))
1718 while (!sp.escMatch('E'))
1720 ret.addOr(new oneChar(sp.c));
1724 else if (sp.escMatch('d'))
1726 ret.addOr(new Range('0', '9'));
1728 else if (sp.escMatch('s'))
1730 ret.addOr(new oneChar((char) 32));
1731 ret.addOr(new Range((char) 8, (char) 10));
1732 ret.addOr(new oneChar((char) 13));
1734 else if (sp.escMatch('w'))
1736 ret.addOr(new Range('a', 'z'));
1737 ret.addOr(new Range('A', 'Z'));
1738 ret.addOr(new Range('0', '9'));
1739 ret.addOr(new oneChar('_'));
1741 else if (sp.escMatch('D'))
1743 ret.addOr(new Range((char) 0, (char) 47));
1744 ret.addOr(new Range((char) 58, (char) 65535));
1746 else if (sp.escMatch('S'))
1748 ret.addOr(new Range((char) 0, (char) 7));
1749 ret.addOr(new Range((char) 11, (char) 12));
1750 ret.addOr(new Range((char) 14, (char) 31));
1751 ret.addOr(new Range((char) 33, (char) 65535));
1753 else if (sp.escMatch('W'))
1755 ret.addOr(new Range((char) 0, (char) 64));
1756 ret.addOr(new Range((char) 91, (char) 94));
1757 ret.addOr(new oneChar((char) 96));
1758 ret.addOr(new Range((char) 123, (char) 65535));
1760 else if (sp.escMatch('x') && next2Hex(sp))
1763 int d = getHexDigit(sp);
1765 d = 16 * d + getHexDigit(sp);
1766 ret.addOr(new oneChar((char) d));
1768 else if (sp.escMatch('a'))
1770 ret.addOr(new oneChar((char) 7));
1772 else if (sp.escMatch('f'))
1774 ret.addOr(new oneChar((char) 12));
1776 else if (sp.escMatch('e'))
1778 ret.addOr(new oneChar((char) 27));
1780 else if (sp.escMatch('n'))
1782 ret.addOr(new oneChar('\n'));
1784 else if (sp.escMatch('t'))
1786 ret.addOr(new oneChar('\t'));
1788 else if (sp.escMatch('r'))
1790 ret.addOr(new oneChar('\r'));
1792 else if (sp.escMatch('c'))
1795 if (sp.c < Ctrl.cmap.length)
1797 ret.addOr(new oneChar(Ctrl.cmap[sp.c]));
1801 ret.addOr(new oneChar(sp.c));
1804 else if (isOctalString(sp))
1808 d = 8 * d + sp.c - '0';
1809 StrPos sp2 = new StrPos(sp);
1811 if (isOctalDigit(sp2, false))
1814 d = 8 * d + sp.c - '0';
1816 ret.addOr(new oneChar((char) d));
1820 ret.addOr(new oneChar(sp.c));
1828 * Converts the stored Pattern to a String -- this is a decompile. Note that
1829 * \t and \n will really print out here, Not just the two character
1830 * representations. Also be prepared to see some strange output if your
1831 * characters are not printable.
1834 public String toString()
1836 if (false && thePattern == null)
1842 StringBuffer sb = new StringBuffer();
1843 if (esc != Pattern.ESC)
1849 if (gFlag || mFlag || !dotDoesntMatchCR || sFlag || ignoreCase
1850 || dontMatchInQuotes || optimized())
1861 if (sFlag || !dotDoesntMatchCR)
1865 if (dontMatchInQuotes)
1879 String patstr = thePattern.toString();
1880 if (esc != Pattern.ESC)
1882 patstr = reEscape(patstr, Pattern.ESC, esc);
1885 return sb.toString();
1889 // Re-escape Pattern, allows us to use a different escape
1891 static String reEscape(String s, char oldEsc, char newEsc)
1893 if (oldEsc == newEsc)
1898 StringBuffer sb = new StringBuffer();
1899 for (i = 0; i < s.length(); i++)
1901 if (s.charAt(i) == oldEsc && i + 1 < s.length())
1903 if (s.charAt(i + 1) == oldEsc)
1910 sb.append(s.charAt(i + 1));
1914 else if (s.charAt(i) == newEsc)
1921 sb.append(s.charAt(i));
1924 return sb.toString();
1928 * This method implements FilenameFilter, allowing one to use a Regex to
1929 * search through a directory using File.list. There is a FileRegex now that
1932 * @see com.stevesoft.pat.FileRegex
1935 public boolean accept(File dir, String s)
1940 /** The version of this package */
1941 final static public String version()
1943 return "lgpl release 1.5.3";
1947 * Once this method is called, the state of variables ignoreCase and
1948 * dontMatchInQuotes should not be changed as the results will be
1949 * unpredictable. However, search and matchAt will run more quickly. Note that
1950 * you can check to see if the pattern has been optimized by calling the
1951 * optimized() method.
1953 * This method will attempt to rewrite your pattern in a way that makes it
1954 * faster (not all patterns execute at the same speed). In general,
1955 * "(?: ... )" will be faster than "( ... )" so if you don't need the
1956 * backreference, you should group using the former pattern.
1958 * It will also introduce new pattern elements that you can't get to
1959 * otherwise, for example if you have a large table of strings, i.e. the
1960 * months of the year "(January|February|...)" optimize() will make a
1961 * Hashtable that takes it to the next appropriate pattern element --
1962 * eliminating the need for a linear search.
1964 * @see com.stevesoft.pat.Regex#optimized
1965 * @see com.stevesoft.pat.Regex#ignoreCase
1966 * @see com.stevesoft.pat.Regex#dontMatchInQuotes
1967 * @see com.stevesoft.pat.Regex#matchAt
1968 * @see com.stevesoft.pat.Regex#search
1970 public void optimize()
1972 if (optimized() || thePattern == null)
1976 minMatch = new patInt(0); // thePattern.countMinChars();
1977 thePattern = RegOpt.opt(thePattern, ignoreCase, dontMatchInQuotes);
1978 skipper = Skip.findSkip(this);
1979 // RegOpt.setParents(this);
1986 * This function returns true if the optimize method has been called.
1988 public boolean optimized()
1990 return minMatch != null;
1994 * A bit of syntactic surgar for those who want to make their code look more
1995 * perl-like. To use this initialize your Regex object by saying:
1998 * Regex r1 = Regex.perlCode("s/hello/goodbye/");
1999 * Regex r2 = Regex.perlCode("s'fish'frog'i");
2000 * Regex r3 = Regex.perlCode("m'hello');
2003 * The i for ignoreCase is supported in this syntax, as well as m, s, and x.
2004 * The g flat is a bit of a special case.
2006 * If you wish to replace all occurences of a pattern, you do not put a 'g' in
2007 * the perlCode, but call Regex's replaceAll method.
2009 * If you wish to simply and only do a search for r2's pattern, you can do
2010 * this by calling the searchFrom method method repeatedly, or by calling
2011 * search repeatedly if the g flag is set.
2013 * Note: Currently perlCode does <em>not</em> support the (?e=#) syntax for
2014 * changing the escape character.
2017 public static Regex perlCode(String s)
2019 // this file is big enough, see parsePerl.java
2020 // for this function.
2021 return parsePerl.parse(s);
2024 static final char back_slash = '\\';
2027 * Checks to see if there are only literal and no special pattern elements in
2030 public boolean isLiteral()
2032 Pattern x = thePattern;
2035 if (x instanceof oneChar)
2039 else if (x instanceof Skipped)
2053 * You only need to know about this if you are inventing your own pattern
2056 public patInt countMinChars()
2058 return thePattern.countMinChars();
2062 * You only need to know about this if you are inventing your own pattern
2065 public patInt countMaxChars()
2067 return thePattern.countMaxChars();
2070 boolean isHexDigit(StrPos sp)
2074 && ((sp.c >= '0' && sp.c <= '9')
2075 || (sp.c >= 'a' && sp.c <= 'f') || (sp.c >= 'A' && sp.c <= 'F'));
2079 boolean isOctalDigit(StrPos sp, boolean first)
2081 boolean r = !sp.eos && !(first ^ sp.dontMatch) && sp.c >= '0'
2086 int getHexDigit(StrPos sp)
2088 if (sp.c >= '0' && sp.c <= '9')
2092 if (sp.c >= 'a' && sp.c <= 'f')
2094 return sp.c - 'a' + 10;
2096 return sp.c - 'A' + 10;
2099 boolean next2Hex(StrPos sp)
2101 StrPos sp2 = new StrPos(sp);
2103 if (!isHexDigit(sp2))
2108 if (!isHexDigit(sp2))
2115 boolean isOctalString(StrPos sp)
2117 if (!isOctalDigit(sp, true))
2121 StrPos sp2 = new StrPos(sp);
2123 if (!isOctalDigit(sp2, false))