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;
19 /** Matches a Unicode punctuation character. */
20 class UnicodePunct extends UniValidator
23 public int validate(StringLike s, int from, int to)
25 return from < s.length() && Prop.isPunct(s.charAt(from)) ? to : -1;
29 /** Matches a Unicode white space character. */
30 class UnicodeWhite extends UniValidator
33 public int validate(StringLike s, int from, int to)
35 return from < s.length() && Prop.isWhite(s.charAt(from)) ? to : -1;
40 * Matches a character that is not a Unicode punctuation character.
42 class NUnicodePunct extends UniValidator
45 public int validate(StringLike s, int from, int to)
47 return from < s.length() && !Prop.isPunct(s.charAt(from)) ? to : -1;
52 * Matches a character that is not a Unicode white space character.
54 class NUnicodeWhite extends UniValidator
57 public int validate(StringLike s, int from, int to)
59 return from < s.length() && !Prop.isWhite(s.charAt(from)) ? to : -1;
63 /** Matches a Unicode word character: an alphanumeric or underscore. */
64 class UnicodeW extends UniValidator
67 public int validate(StringLike s, int from, int to)
69 if (from >= s.length())
73 char c = s.charAt(from);
74 return (Prop.isAlphabetic(c) || Prop.isDecimalDigit(c) || c == '_') ? to
79 /** Matches a character that is not a Unicode alphanumeric or underscore. */
80 class NUnicodeW extends UniValidator
83 public int validate(StringLike s, int from, int to)
85 if (from >= s.length())
89 char c = s.charAt(from);
90 return !(Prop.isAlphabetic(c) || Prop.isDecimalDigit(c) || c == '_') ? to
95 /** Matches a Unicode decimal digit. */
96 class UnicodeDigit extends UniValidator
99 public int validate(StringLike s, int from, int to)
101 return from < s.length() && Prop.isDecimalDigit(s.charAt(from)) ? to
106 /** Matches a character that is not a Unicode digit. */
107 class NUnicodeDigit extends UniValidator
110 public int validate(StringLike s, int from, int to)
112 return from < s.length() && !Prop.isDecimalDigit(s.charAt(from)) ? to
117 /** Matches a Unicode math character. */
118 class UnicodeMath extends UniValidator
121 public int validate(StringLike s, int from, int to)
123 return from < s.length() && Prop.isMath(s.charAt(from)) ? to : -1;
127 /** Matches a non-math Unicode character. */
128 class NUnicodeMath extends UniValidator
131 public int validate(StringLike s, int from, int to)
133 return from < s.length() && !Prop.isMath(s.charAt(from)) ? to : -1;
137 /** Matches a Unicode currency symbol. */
138 class UnicodeCurrency extends UniValidator
141 public int validate(StringLike s, int from, int to)
143 return from < s.length() && Prop.isCurrency(s.charAt(from)) ? to : -1;
147 /** Matches a non-currency symbol Unicode character. */
148 class NUnicodeCurrency extends UniValidator
151 public int validate(StringLike s, int from, int to)
153 return from < s.length() && !Prop.isCurrency(s.charAt(from)) ? to : -1;
157 /** Matches a Unicode alphabetic character. */
158 class UnicodeAlpha extends UniValidator
161 public int validate(StringLike s, int from, int to)
163 return from < s.length() && Prop.isAlphabetic(s.charAt(from)) ? to : -1;
167 /** Matches a non-alphabetic Unicode character. */
168 class NUnicodeAlpha extends UniValidator
171 public int validate(StringLike s, int from, int to)
173 return from < s.length() && !Prop.isAlphabetic(s.charAt(from)) ? to
178 /** Matches an upper case Unicode character. */
179 class UnicodeUpper extends UniValidator
182 public int validate(StringLike s, int from, int to)
184 return from < s.length() && isUpper(s.charAt(from)) ? to : -1;
187 final boolean isUpper(char c)
189 return c == CaseMgr.toUpperCase(c) && c != CaseMgr.toLowerCase(c);
193 /** Matches an upper case Unicode character. */
194 class UnicodeLower extends UniValidator
197 public int validate(StringLike s, int from, int to)
199 return from < s.length() && isLower(s.charAt(from)) ? to : -1;
202 final boolean isLower(char c)
204 return c != CaseMgr.toUpperCase(c) && c == CaseMgr.toLowerCase(c);
209 * Regex provides the parser which constructs the linked list of Pattern classes
212 * For the purpose of this documentation, the fact that java interprets the
213 * backslash will be ignored. In practice, however, you will need a double
214 * backslash to obtain a string that contains a single backslash character.
215 * Thus, the example pattern "\b" should really be typed as "\\b" inside java
218 * Note that Regex is part of package "com.stevesoft.pat". To use it, simply
219 * import com.stevesoft.pat.Regex at the top of your file.
221 * Regex is made with a constructor that takes a String that defines the regular
222 * expression. Thus, for example
225 * Regex r = new Regex("[a-c]*");
228 * matches any number of characters so long as the are 'a', 'b', or 'c').
230 * To attempt to match the Pattern to a given string, you can use either the
231 * search(String) member function, or the matchAt(String,int position) member
232 * function. These functions return a boolean which tells you whether or not the
233 * thing worked, and sets the methods "charsMatched()" and "matchedFrom()" in
234 * the Regex object appropriately.
236 * The portion of the string before the match can be obtained by the left()
237 * member, and the portion after the match can be obtained by the right()
240 * Essentially, this package implements a syntax that is very much like the perl
241 * 5 regular expression syntax.
246 * Regex r = new Regex("x(a|b)y");
247 * r.matchAt("xay", 0);
248 * System.out.println("sub = " + r.stringMatched(1));
251 * The above would print "sub = a".
254 * r.left() // would return "x"
255 * r.right() // would return "y"
259 * Differences between this package and perl5:<br>
260 * The extended Pattern for setting flags, is now supported, but the flags are
261 * different. "(?i)" tells the pattern to ignore case, "(?Q)" sets the
262 * "dontMatchInQuotes" flag, and "(?iQ)" sets them both. You can change the
263 * escape character. The pattern
275 * , but note that the sequence
281 * <b>must</b> occur at the very beginning of the pattern. There may be other
282 * small differences as well. I will either make my package conform or note them
283 * as I become aware of them.
285 * This package supports additional patterns not in perl5: <center>
290 * <td>This matches all characters between the '(' character and the balancing
291 * ')' character. Thus, it will match "()" as well as "(())". The balancing
292 * characters are arbitrary, thus (?@{}) matches on "{}" and "{{}}".</td>
296 * <td>Moves the pointer backwards within the text. This allows you to make a
297 * "look behind." It fails if it attempts to move to a position before the
298 * beginning of the string. "x(?<1)" is equivalent to "(?=x)". The number, 1
299 * in this example, is the number of characters to move backwards.</td>
303 * @author Steven R. Brandt
304 * @version package com.stevesoft.pat, release 1.5.3
307 public class Regex extends RegRes implements FilenameFilter
310 * BackRefOffset gives the identity number of the first pattern. Version 1.0
311 * used zero, version 1.1 uses 1 to be more compatible with perl.
313 static int BackRefOffset = 1;
315 private static Pattern none = new NoPattern();
317 Pattern thePattern = none;
319 patInt minMatch = new patInt(0);
321 static Hashtable validators = new Hashtable();
324 define("p", "(?>1)", new UnicodePunct());
325 define("P", "(?>1)", new NUnicodePunct());
326 define("s", "(?>1)", new UnicodeWhite());
327 define("S", "(?>1)", new NUnicodeWhite());
328 define("w", "(?>1)", new UnicodeW());
329 define("W", "(?>1)", new NUnicodeW());
330 define("d", "(?>1)", new UnicodeDigit());
331 define("D", "(?>1)", new NUnicodeDigit());
332 define("m", "(?>1)", new UnicodeMath());
333 define("M", "(?>1)", new NUnicodeMath());
334 define("c", "(?>1)", new UnicodeCurrency());
335 define("C", "(?>1)", new NUnicodeCurrency());
336 define("a", "(?>1)", new UnicodeAlpha());
337 define("A", "(?>1)", new NUnicodeAlpha());
338 define("uc", "(?>1)", new UnicodeUpper());
339 define("lc", "(?>1)", new UnicodeLower());
342 /** Set the dontMatch in quotes flag. */
343 public void setDontMatchInQuotes(boolean b)
345 dontMatchInQuotes = b;
348 /** Find out if the dontMatchInQuotes flag is enabled. */
349 public boolean getDontMatchInQuotes()
351 return dontMatchInQuotes;
354 boolean dontMatchInQuotes = false;
357 * Set the state of the ignoreCase flag. If set to true, then the pattern
358 * matcher will ignore case when searching for a match.
360 public void setIgnoreCase(boolean b)
366 * Get the state of the ignoreCase flag. Returns true if we are ignoring the
367 * case of the pattern, false otherwise.
369 public boolean getIgnoreCase()
374 boolean ignoreCase = false;
376 static boolean defaultMFlag = false;
379 * Set the default value of the m flag. If it is set to true, then the MFlag
380 * will be on for any regex search executed.
382 public static void setDefaultMFlag(boolean mFlag)
384 defaultMFlag = mFlag;
388 * Get the default value of the m flag. If it is set to true, then the MFlag
389 * will be on for any regex search executed.
391 public static boolean getDefaultMFlag()
397 * Initializes the object without a Pattern. To supply a Pattern use
400 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
407 * Create and compile a Regex, but do not throw any exceptions. If you wish to
408 * have exceptions thrown for syntax errors, you must use the Regex(void)
409 * constructor to create the Regex object, and then call the compile method.
410 * Therefore, you should only call this method when you know your pattern is
411 * right. I will probably become more like
413 * @see com.stevesoft.pat.Regex#search(java.lang.String)
414 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
416 public Regex(String s)
421 } catch (RegSyntax rs)
426 ReplaceRule rep = null;
429 * Create and compile both a Regex and a ReplaceRule.
431 * @see com.stevesoft.pat.ReplaceRule
432 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
434 public Regex(String s, String rp)
437 rep = ReplaceRule.perlCode(rp);
441 * Create and compile a Regex, but give it the ReplaceRule specified. This
442 * allows the user finer control of the Replacement process, if that is
445 * @see com.stevesoft.pat.ReplaceRule
446 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
448 public Regex(String s, ReplaceRule rp)
455 * Change the ReplaceRule of this Regex by compiling a new one using String
458 public void setReplaceRule(String rp)
460 rep = ReplaceRule.perlCode(rp);
461 repr = null; // Clear Replacer history
464 /** Change the ReplaceRule of this Regex to rp. */
465 public void setReplaceRule(ReplaceRule rp)
471 * Test to see if a custom defined rule exists.
473 * @see com.stevesoft.pat#define(java.lang.String,java.lang.String,Validator)
475 public static boolean isDefined(String nm)
477 return validators.get(nm) != null;
481 * Removes a custom defined rule.
483 * @see com.stevesoft.pat#define(java.lang.String,java.lang.String,Validator)
485 public static void undefine(String nm)
487 validators.remove(nm);
491 * Defines a method to create a new rule. See test/deriv2.java and
492 * test/deriv3.java for examples of how to use it.
494 public static void define(String nm, String pat, Validator v)
497 validators.put(nm, v);
501 * Defines a shorthand for a pattern. The pattern will be invoked by a string
502 * that has the form "(??"+nm+")".
504 public static void define(String nm, String pat)
506 validators.put(nm, pat);
509 /** Get the current ReplaceRule. */
510 public ReplaceRule getReplaceRule()
515 Replacer repr = null;
517 final Replacer _getReplacer()
519 return repr == null ? repr = new Replacer() : repr;
522 public Replacer getReplacer()
526 repr = new Replacer();
534 * Replace the first occurence of this pattern in String s according to the
537 * @see com.stevesoft.pat.ReplaceRule
538 * @see com.stevesoft.pat.Regex#getReplaceRule()
540 public String replaceFirst(String s)
542 return _getReplacer().replaceFirstRegion(s, this, 0, s.length())
547 * Replace the first occurence of this pattern in String s beginning with
548 * position pos according to the ReplaceRule.
550 * @see com.stevesoft.pat.ReplaceRule
551 * @see com.stevesoft.pat.Regex#getReplaceRule()
553 public String replaceFirstFrom(String s, int pos)
555 return _getReplacer().replaceFirstRegion(s, this, pos, s.length())
560 * Replace the first occurence of this pattern in String s beginning with
561 * position start and ending with end according to the ReplaceRule.
563 * @see com.stevesoft.pat.ReplaceRule
564 * @see com.stevesoft.pat.Regex#getReplaceRule()
566 public String replaceFirstRegion(String s, int start, int end)
568 return _getReplacer().replaceFirstRegion(s, this, start, end)
573 * Replace all occurences of this pattern in String s according to the
576 * @see com.stevesoft.pat.ReplaceRule
577 * @see com.stevesoft.pat.Regex#getReplaceRule()
579 public String replaceAll(String s)
581 return _getReplacer().replaceAllRegion(s, this, 0, s.length())
585 public StringLike replaceAll(StringLike s)
587 return _getReplacer().replaceAllRegion(s, this, 0, s.length());
591 * Replace all occurences of this pattern in String s beginning with position
592 * pos according to the ReplaceRule.
594 * @see com.stevesoft.pat.ReplaceRule
595 * @see com.stevesoft.pat.Regex#getReplaceRule()
597 public String replaceAllFrom(String s, int pos)
599 return _getReplacer().replaceAllRegion(s, this, pos, s.length())
604 * Replace all occurences of this pattern in String s beginning with position
605 * start and ending with end according to the ReplaceRule.
607 * @see com.stevesoft.pat.ReplaceRule
608 * @see com.stevesoft.pat.Regex#getReplaceRule()
610 public String replaceAllRegion(String s, int start, int end)
612 return _getReplacer().replaceAllRegion(s, this, start, end).toString();
615 /** Essentially clones the Regex object */
616 public Regex(Regex r)
619 dontMatchInQuotes = r.dontMatchInQuotes;
621 ignoreCase = r.ignoreCase;
629 rep = (ReplaceRule) r.rep.clone();
632 * try { compile(r.toString()); } catch(RegSyntax r_) {}
634 thePattern = r.thePattern.clone(new Hashtable());
635 minMatch = r.minMatch;
640 * By default, the escape character is the backslash, but you can make it
641 * anything you want by setting this variable.
643 public char esc = Pattern.ESC;
646 * This method compiles a regular expression, making it possible to call the
647 * search or matchAt methods.
649 * @exception com.stevesoft.pat.RegSyntax
650 * is thrown if a syntax error is encountered in the pattern. For
651 * example, "x{3,1}" or "*a" are not valid patterns.
652 * @see com.stevesoft.pat.Regex#search
653 * @see com.stevesoft.pat.Regex#matchAt
655 public void compile(String prepat) throws RegSyntax
657 String postpat = parsePerl.codify(prepat, true);
658 String pat = postpat == null ? prepat : postpat;
661 dontMatchInQuotes = false;
662 Rthings mk = new Rthings(this);
668 minMatch = new patInt(0);
669 StrPos sp = new StrPos(pat, 0);
670 if (sp.incMatch("(?e="))
676 newpat = reEscape(pat.substring(6), newEsc, Pattern.ESC);
679 else if (esc != Pattern.ESC)
681 newpat = reEscape(pat, esc, Pattern.ESC);
683 thePattern = _compile(newpat, mk);
684 numSubs_ = mk.val - offset;
689 * If a Regex is compared against a Regex, a check is done to see that the
690 * patterns are equal as well as the most recent match. If a Regex is compare
691 * with a RegRes, only the result of the most recent match is compared.
694 public boolean equals(Object o)
696 if (o instanceof Regex)
698 if (toString().equals(o.toString()))
700 return super.equals(o);
709 return super.equals(o);
713 /** A clone by any other name would smell as sweet. */
715 public Object clone()
717 return new Regex(this);
720 /** Return a clone of the underlying RegRes object. */
721 public RegRes result()
723 return (RegRes) super.clone();
726 // prep sets global variables of class
727 // Pattern so that it can access them
728 // during an attempt at a match
729 Pthings pt = new Pthings();
731 final Pthings prep(StringLike s)
734 pt.lastPos = matchedTo();
739 if ((s == null ? null : s.unwrap()) != (src == null ? null : s.unwrap()))
744 pt.dotDoesntMatchCR = dotDoesntMatchCR && (!sFlag);
745 pt.mFlag = (mFlag | defaultMFlag);
746 pt.ignoreCase = ignoreCase;
748 if (pt.marks != null)
750 for (int i = 0; i < pt.marks.length; i++)
756 pt.nMarks = numSubs_;
758 if (dontMatchInQuotes)
770 * Attempt to match a Pattern beginning at a specified location within the
773 * @see com.stevesoft.pat.Regex#search
775 public boolean matchAt(String s, int start_pos)
777 return _search(s, start_pos, start_pos);
781 * Attempt to match a Pattern beginning at a specified location within the
784 * @see com.stevesoft.pat.Regex#search
786 public boolean matchAt(StringLike s, int start_pos)
788 return _search(s, start_pos, start_pos);
792 * Search through a String for the first occurrence of a match.
794 * @see com.stevesoft.pat.Regex#searchFrom
795 * @see com.stevesoft.pat.Regex#matchAt
797 public boolean search(String s)
801 throw new NullPointerException(
803 .getString("exception.null_string_given_to_regex_search"));
805 return _search(s, 0, s.length());
808 public boolean search(StringLike sl)
812 throw new NullPointerException(
814 .getString("exception.null_string_like_given_to_regex_search"));
816 return _search(sl, 0, sl.length());
819 public boolean reverseSearch(String s)
823 throw new NullPointerException(
825 .getString("exception.null_string_given_to_regex_reverse_search"));
827 return _reverseSearch(s, 0, s.length());
830 public boolean reverseSearch(StringLike sl)
834 throw new NullPointerException(
836 .getString("exception.null_string_like_given_to_regex_reverse_search"));
838 return _reverseSearch(sl, 0, sl.length());
842 * Search through a String for the first occurence of a match, but start at
849 public boolean searchFrom(String s, int start)
853 throw new NullPointerException(
855 .getString("exception.null_string_like_given_to_regex_search_from"));
857 return _search(s, start, s.length());
860 public boolean searchFrom(StringLike 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());
872 * Search through a region of a String for the first occurence of a match.
874 public boolean searchRegion(String s, int start, int end)
878 throw new NullPointerException(
880 .getString("exception.null_string_like_given_to_regex_search_region"));
882 return _search(s, start, end);
886 * Set this to change the default behavior of the "." pattern. By default it
887 * now matches perl's behavior and fails to match the '\n' character.
889 public static boolean dotDoesntMatchCR = true;
895 boolean gFlag = false;
897 /** Set the 'g' flag */
898 public void setGFlag(boolean b)
903 /** Get the state of the 'g' flag. */
904 public boolean getGFlag()
909 boolean sFlag = false;
911 /** Get the state of the sFlag */
912 public boolean getSFlag()
917 boolean mFlag = false;
919 /** Get the state of the sFlag */
920 public boolean getMFlag()
925 final boolean _search(String s, int start, int end)
927 return _search(new StringWrap(s), start, end);
930 final boolean _search(StringLike s, int start, int end)
932 if (gFlag && gFlagto > 0 && gFlags != null
933 && s.unwrap() == gFlags.unwrap())
939 Pthings pt = prep(s);
941 int up = (minMatch == null ? end : end - minMatch.i);
943 if (up < start && end >= start)
950 for (int i = start; i <= up; i++)
952 charsMatched_ = thePattern.matchAt(s, i, pt);
953 if (charsMatched_ >= 0)
955 matchFrom_ = thePattern.mfrom;
957 gFlagto = matchFrom_ + charsMatched_;
959 return didMatch_ = true;
966 for (int i = start; i <= up; i++)
968 i = skipper.find(src, i, up);
971 charsMatched_ = matchFrom_ = -1;
972 return didMatch_ = false;
974 charsMatched_ = thePattern.matchAt(s, i, pt);
975 if (charsMatched_ >= 0)
977 matchFrom_ = thePattern.mfrom;
979 gFlagto = matchFrom_ + charsMatched_;
981 return didMatch_ = true;
985 return didMatch_ = false;
989 * final boolean _search(LongStringLike s,long start,long end) { if(gFlag &&
990 * gFlagto > 0 && s==gFlags) start = gFlagto; gFlags = null;
992 * Pthings pt=prep(s);
994 * int up = end;//(minMatch == null ? end : end-minMatch.i);
996 * if(up < start && end >= start) up = start;
998 * if(skipper == null) { for(long i=start;i<=up;i++) { charsMatched_ =
999 * thePattern.matchAt(s,i,pt); if(charsMatched_ >= 0) { matchFrom_ =
1000 * thePattern.mfrom; marks = pt.marks; gFlagto = matchFrom_+charsMatched_;
1001 * return didMatch_=true; } } } else { pt.no_check = true; for(long
1002 * i=start;i<=up;i++) { i = skipper.find(src,i,up); if(i<0) { charsMatched_ =
1003 * matchFrom_ = -1; return didMatch_ = false; } charsMatched_ =
1004 * thePattern.matchAt(s,i,pt); if(charsMatched_ >= 0) { matchFrom_ =
1005 * thePattern.mfrom; marks = pt.marks; gFlagto = matchFrom_+charsMatched_;
1006 * gFlags = s; return didMatch_=true; } else { i = s.adjustIndex(i); up =
1007 * s.adjustEnd(i); } } } return didMatch_=false; }
1010 boolean _reverseSearch(String s, int start, int end)
1012 return _reverseSearch(new StringWrap(s), start, end);
1015 boolean _reverseSearch(StringLike s, int start, int end)
1017 if (gFlag && gFlagto > 0 && s.unwrap() == gFlags.unwrap())
1022 Pthings pt = prep(s);
1023 for (int i = end; i >= start; i--)
1025 charsMatched_ = thePattern.matchAt(s, i, pt);
1026 if (charsMatched_ >= 0)
1028 matchFrom_ = thePattern.mfrom;
1030 gFlagto = matchFrom_ - 1;
1032 return didMatch_ = true;
1035 return didMatch_ = false;
1038 // This routine sets the cbits variable
1039 // of class Pattern. Cbits is true for
1040 // the bit corresponding to a character inside
1042 static StringLike lasts = null;
1044 static BitSet lastbs = null;
1046 static void setCbits(StringLike s, Pthings pt)
1053 BitSet bs = new BitSet(s.length());
1055 boolean setBit = false;
1056 for (int i = 0; i < s.length(); i++)
1062 char c = s.charAt(i);
1063 if (!setBit && c == '"')
1069 else if (!setBit && c == '\'')
1075 else if (setBit && c == qc)
1079 else if (setBit && c == '\\' && i + 1 < s.length())
1088 pt.cbits = lastbs = bs;
1092 // Wanted user to over-ride this in alpha version,
1093 // but it wasn't really necessary because of this trick:
1098 return getClass().getDeclaredConstructor().newInstance();
1099 } catch (InstantiationException ie)
1102 } catch (IllegalAccessException iae)
1105 } catch (ReflectiveOperationException roe)
1112 * Only needed for creating your own extensions of Regex. This method adds the
1113 * next Pattern in the chain of patterns or sets the Pattern if it is the
1116 protected void add(Pattern p2)
1130 * You only need to use this method if you are creating your own extentions to
1131 * Regex. compile1 compiles one Pattern element, it can be over-ridden to
1132 * allow the Regex compiler to understand new syntax. See deriv.java for an
1133 * example. This routine is the heart of class Regex. Rthings has one integer
1134 * member called intValue, it is used to keep track of the number of ()'s in
1137 * @exception com.stevesoft.pat.RegSyntax
1138 * is thrown when a nonsensensical pattern is supplied. For
1139 * example, a pattern beginning with *.
1141 protected void compile1(StrPos sp, Rthings mk) throws RegSyntax
1146 add(matchBracket(sp));
1148 else if (sp.match('|'))
1156 p = new NullPattern();
1161 else if (sp.incMatch("(?<"))
1163 patInt i = sp.getPatInt();
1166 RegSyntaxError.endItAll("No int after (?<");
1168 add(new Backup(i.intValue()));
1171 RegSyntaxError.endItAll("No ) after (?<");
1174 else if (sp.incMatch("(?>"))
1176 patInt i = sp.getPatInt();
1179 RegSyntaxError.endItAll("No int after (?>");
1181 add(new Backup(-i.intValue()));
1184 RegSyntaxError.endItAll("No ) after (?<");
1187 else if (sp.incMatch("(?@"))
1195 RegSyntaxError.endItAll("(?@ does not have closing paren");
1197 add(new Group(op, cl));
1199 else if (sp.incMatch("(?#"))
1201 while (!sp.match(')'))
1206 else if (sp.dontMatch && sp.c == 'w')
1208 // Regex r = new Regex();
1209 // r._compile("[a-zA-Z0-9_]",mk);
1210 // add(new Goop("\\w",r.thePattern));
1211 Bracket b = new Bracket(false);
1212 b.addOr(new Range('a', 'z'));
1213 b.addOr(new Range('A', 'Z'));
1214 b.addOr(new Range('0', '9'));
1215 b.addOr(new oneChar('_'));
1218 else if (sp.dontMatch && sp.c == 'G')
1222 else if (sp.dontMatch && sp.c == 's')
1224 // Regex r = new Regex();
1225 // r._compile("[ \t\n\r\b]",mk);
1226 // add(new Goop("\\s",r.thePattern));
1227 Bracket b = new Bracket(false);
1228 b.addOr(new oneChar((char) 32));
1229 b.addOr(new Range((char) 8, (char) 10));
1230 b.addOr(new oneChar((char) 13));
1233 else if (sp.dontMatch && sp.c == 'd')
1235 // Regex r = new Regex();
1236 // r._compile("[0-9]",mk);
1237 // add(new Goop("\\d",r.thePattern));
1238 Range digit = new Range('0', '9');
1239 digit.printBrackets = true;
1242 else if (sp.dontMatch && sp.c == 'W')
1244 // Regex r = new Regex();
1245 // r._compile("[^a-zA-Z0-9_]",mk);
1246 // add(new Goop("\\W",r.thePattern));
1247 Bracket b = new Bracket(true);
1248 b.addOr(new Range('a', 'z'));
1249 b.addOr(new Range('A', 'Z'));
1250 b.addOr(new Range('0', '9'));
1251 b.addOr(new oneChar('_'));
1254 else if (sp.dontMatch && sp.c == 'S')
1256 // Regex r = new Regex();
1257 // r._compile("[^ \t\n\r\b]",mk);
1258 // add(new Goop("\\S",r.thePattern));
1259 Bracket b = new Bracket(true);
1260 b.addOr(new oneChar((char) 32));
1261 b.addOr(new Range((char) 8, (char) 10));
1262 b.addOr(new oneChar((char) 13));
1265 else if (sp.dontMatch && sp.c == 'D')
1267 // Regex r = new Regex();
1268 // r._compile("[^0-9]",mk);
1269 // add(new Goop("\\D",r.thePattern));
1270 Bracket b = new Bracket(true);
1271 b.addOr(new Range('0', '9'));
1274 else if (sp.dontMatch && sp.c == 'B')
1276 Regex r = new Regex();
1277 r._compile("(?!" + back_slash + "b)", mk);
1280 else if (isOctalString(sp))
1284 d = 8 * d + sp.c - '0';
1285 StrPos sp2 = new StrPos(sp);
1287 if (isOctalDigit(sp2, false))
1290 d = 8 * d + sp.c - '0';
1292 add(new oneChar((char) d));
1294 else if (sp.dontMatch && sp.c >= '1' && sp.c <= '9')
1296 int iv = sp.c - '0';
1297 StrPos s2 = new StrPos(sp);
1299 if (!s2.dontMatch && s2.c >= '0' && s2.c <= '9')
1301 iv = 10 * iv + (s2.c - '0');
1304 add(new BackMatch(iv));
1306 else if (sp.dontMatch && sp.c == 'b')
1308 add(new Boundary());
1310 else if (sp.match('\b'))
1312 add(new Boundary());
1314 else if (sp.match('$'))
1318 else if (sp.dontMatch && sp.c == 'Z')
1320 add(new End(false));
1322 else if (sp.match('.'))
1326 else if (sp.incMatch("(??"))
1328 StringBuffer sb = new StringBuffer();
1329 StringBuffer sb2 = new StringBuffer();
1330 while (!sp.match(')') && !sp.match(':'))
1335 if (sp.incMatch(":"))
1337 while (!sp.match(')'))
1343 String sbs = sb.toString();
1344 if (validators.get(sbs) instanceof String)
1346 String pat = (String) validators.get(sbs);
1347 Regex r = newRegex();
1348 Rthings rth = new Rthings(this);
1349 rth.noBackRefs = true;
1350 r._compile(pat, rth);
1355 Custom cm = new Custom(sb.toString());
1358 Validator v2 = cm.v.arg(sb2.toString());
1361 v2.argsave = sb2.toString();
1362 String p = cm.v.pattern;
1366 Regex r = newRegex();
1367 Rthings rth = new Rthings(this);
1368 rth.noBackRefs = true;
1369 r._compile(cm.v.pattern, rth);
1370 cm.sub = r.thePattern;
1371 cm.sub.add(new CustomEndpoint(cm));
1372 cm.sub.setParent(cm);
1377 else if (sp.match('('))
1380 Regex r = newRegex();
1383 if (sp.incMatch("?:"))
1387 else if (sp.incMatch("?="))
1389 r.or = new lookAhead(false);
1391 else if (sp.incMatch("?!"))
1393 r.or = new lookAhead(true);
1395 else if (sp.match('?'))
1402 mk.ignoreCase = true;
1406 mk.dontMatchInQuotes = true;
1410 mk.optimizeMe = true;
1425 } while (!sp.match(')') && !sp.eos);
1428 if (sp.eos) // throw new RegSyntax
1430 RegSyntaxError.endItAll("Unclosed ()");
1434 { // just ordinary parenthesis
1435 r.or = mk.noBackRefs ? new Or() : new OrMark(mk.val++);
1439 add(r._compile(sp, mk));
1442 else if (sp.match('^'))
1444 add(new Start(true));
1446 else if (sp.dontMatch && sp.c == 'A')
1448 add(new Start(false));
1450 else if (sp.match('*'))
1452 addMulti(new patInt(0), new patInf());
1454 else if (sp.match('+'))
1456 addMulti(new patInt(1), new patInf());
1458 else if (sp.match('?'))
1460 addMulti(new patInt(0), new patInt(1));
1462 else if (sp.match('{'))
1464 boolean bad = false;
1465 StrPos sp2 = new StrPos(sp);
1466 // StringBuffer sb = new StringBuffer();
1468 patInt i1 = sp.getPatInt();
1479 * RegSyntaxError.endItAll( "String \"{"+i2+ "\" should be followed
1491 i2 = sp.getPatInt();
1494 if (i1 == null || i2 == null)
1497 * throw new RegSyntax("Badly formatted Multi: " +"{"+i1+","+i2+"}");
1504 add(new oneChar(sp.c));
1511 else if (sp.escMatch('x') && next2Hex(sp))
1514 int d = getHexDigit(sp);
1516 d = 16 * d + getHexDigit(sp);
1517 add(new oneChar((char) d));
1519 else if (sp.escMatch('c'))
1522 if (sp.c < Ctrl.cmap.length)
1524 add(new oneChar(Ctrl.cmap[sp.c]));
1528 add(new oneChar(sp.c));
1531 else if (sp.escMatch('f'))
1533 add(new oneChar((char) 12));
1535 else if (sp.escMatch('a'))
1537 add(new oneChar((char) 7));
1539 else if (sp.escMatch('t'))
1541 add(new oneChar('\t'));
1543 else if (sp.escMatch('n'))
1545 add(new oneChar('\n'));
1547 else if (sp.escMatch('r'))
1549 add(new oneChar('\r'));
1551 else if (sp.escMatch('b'))
1553 add(new oneChar('\b'));
1555 else if (sp.escMatch('e'))
1557 add(new oneChar((char) 27));
1561 add(new oneChar(sp.c));
1564 RegSyntaxError.endItAll("Unmatched right paren in pattern");
1569 // compiles all Pattern elements, internal method
1570 private Pattern _compile(String pat, Rthings mk) throws RegSyntax
1573 sFlag = mFlag = ignoreCase = gFlag = false;
1574 StrPos sp = new StrPos(pat, 0);
1575 thePattern = _compile(sp, mk);
1584 Pattern _compile(StrPos sp, Rthings mk) throws RegSyntax
1586 while (!(sp.eos || (or != null && sp.match(')'))))
1595 else if (sp.eos && mk.parenLevel != 0)
1597 RegSyntaxError.endItAll("Unclosed Parenthesis! lvl=" + mk.parenLevel);
1603 p = new NullPattern();
1608 return p == null ? new NullPattern() : p;
1611 // add a multi object to the end of the chain
1612 // which applies to the last object
1613 void addMulti(patInt i1, patInt i2) throws RegSyntax
1615 Pattern last, last2;
1616 for (last = p; last != null && last.next != null; last = last.next)
1620 if (last == null || last == p)
1626 for (last2 = p; last2.next != last; last2 = last2.next)
1631 if (last instanceof Multi && i1.intValue() == 0 && i2.intValue() == 1)
1633 ((Multi) last).matchFewest = true;
1635 else if (last instanceof FastMulti && i1.intValue() == 0
1636 && i2.intValue() == 1)
1638 ((FastMulti) last).matchFewest = true;
1640 else if (last instanceof DotMulti && i1.intValue() == 0
1641 && i2.intValue() == 1)
1643 ((DotMulti) last).matchFewest = true;
1645 else if (last instanceof Multi || last instanceof DotMulti
1646 || last instanceof FastMulti)
1648 throw new RegSyntax("Syntax error.");
1650 else if (last2 == null)
1652 p = mkMulti(i1, i2, p);
1656 last2.next = mkMulti(i1, i2, last);
1660 final static Pattern mkMulti(patInt lo, patInt hi, Pattern p)
1663 if (p instanceof Any && p.next == null)
1665 return new DotMulti(lo, hi);
1667 return RegOpt.safe4fm(p) ? (Pattern) new FastMulti(lo, hi, p)
1668 : (Pattern) new Multi(lo, hi, p);
1671 // process the bracket operator
1672 Pattern matchBracket(StrPos sp) throws RegSyntax
1677 ret = new Bracket(true);
1682 ret = new Bracket(false);
1686 // throw new RegSyntax
1687 RegSyntaxError.endItAll("Unmatched []");
1690 while (!sp.eos && !sp.match(']'))
1692 StrPos s1 = new StrPos(sp);
1694 StrPos s1_ = new StrPos(s1);
1696 if (s1.match('-') && !s1_.match(']'))
1698 StrPos s2 = new StrPos(s1);
1702 ret.addOr(new Range(sp.c, s2.c));
1707 else if (sp.escMatch('Q'))
1710 while (!sp.escMatch('E'))
1712 ret.addOr(new oneChar(sp.c));
1716 else if (sp.escMatch('d'))
1718 ret.addOr(new Range('0', '9'));
1720 else if (sp.escMatch('s'))
1722 ret.addOr(new oneChar((char) 32));
1723 ret.addOr(new Range((char) 8, (char) 10));
1724 ret.addOr(new oneChar((char) 13));
1726 else if (sp.escMatch('w'))
1728 ret.addOr(new Range('a', 'z'));
1729 ret.addOr(new Range('A', 'Z'));
1730 ret.addOr(new Range('0', '9'));
1731 ret.addOr(new oneChar('_'));
1733 else if (sp.escMatch('D'))
1735 ret.addOr(new Range((char) 0, (char) 47));
1736 ret.addOr(new Range((char) 58, (char) 65535));
1738 else if (sp.escMatch('S'))
1740 ret.addOr(new Range((char) 0, (char) 7));
1741 ret.addOr(new Range((char) 11, (char) 12));
1742 ret.addOr(new Range((char) 14, (char) 31));
1743 ret.addOr(new Range((char) 33, (char) 65535));
1745 else if (sp.escMatch('W'))
1747 ret.addOr(new Range((char) 0, (char) 64));
1748 ret.addOr(new Range((char) 91, (char) 94));
1749 ret.addOr(new oneChar((char) 96));
1750 ret.addOr(new Range((char) 123, (char) 65535));
1752 else if (sp.escMatch('x') && next2Hex(sp))
1755 int d = getHexDigit(sp);
1757 d = 16 * d + getHexDigit(sp);
1758 ret.addOr(new oneChar((char) d));
1760 else if (sp.escMatch('a'))
1762 ret.addOr(new oneChar((char) 7));
1764 else if (sp.escMatch('f'))
1766 ret.addOr(new oneChar((char) 12));
1768 else if (sp.escMatch('e'))
1770 ret.addOr(new oneChar((char) 27));
1772 else if (sp.escMatch('n'))
1774 ret.addOr(new oneChar('\n'));
1776 else if (sp.escMatch('t'))
1778 ret.addOr(new oneChar('\t'));
1780 else if (sp.escMatch('r'))
1782 ret.addOr(new oneChar('\r'));
1784 else if (sp.escMatch('c'))
1787 if (sp.c < Ctrl.cmap.length)
1789 ret.addOr(new oneChar(Ctrl.cmap[sp.c]));
1793 ret.addOr(new oneChar(sp.c));
1796 else if (isOctalString(sp))
1800 d = 8 * d + sp.c - '0';
1801 StrPos sp2 = new StrPos(sp);
1803 if (isOctalDigit(sp2, false))
1806 d = 8 * d + sp.c - '0';
1808 ret.addOr(new oneChar((char) d));
1812 ret.addOr(new oneChar(sp.c));
1820 * Converts the stored Pattern to a String -- this is a decompile. Note that
1821 * \t and \n will really print out here, Not just the two character
1822 * representations. Also be prepared to see some strange output if your
1823 * characters are not printable.
1826 public String toString()
1828 if (false && thePattern == null)
1834 StringBuffer sb = new StringBuffer();
1835 if (esc != Pattern.ESC)
1841 if (gFlag || mFlag || !dotDoesntMatchCR || sFlag || ignoreCase
1842 || dontMatchInQuotes || optimized())
1853 if (sFlag || !dotDoesntMatchCR)
1857 if (dontMatchInQuotes)
1871 String patstr = thePattern.toString();
1872 if (esc != Pattern.ESC)
1874 patstr = reEscape(patstr, Pattern.ESC, esc);
1877 return sb.toString();
1881 // Re-escape Pattern, allows us to use a different escape
1883 static String reEscape(String s, char oldEsc, char newEsc)
1885 if (oldEsc == newEsc)
1890 StringBuffer sb = new StringBuffer();
1891 for (i = 0; i < s.length(); i++)
1893 if (s.charAt(i) == oldEsc && i + 1 < s.length())
1895 if (s.charAt(i + 1) == oldEsc)
1902 sb.append(s.charAt(i + 1));
1906 else if (s.charAt(i) == newEsc)
1913 sb.append(s.charAt(i));
1916 return sb.toString();
1920 * This method implements FilenameFilter, allowing one to use a Regex to
1921 * search through a directory using File.list. There is a FileRegex now that
1924 * @see com.stevesoft.pat.FileRegex
1927 public boolean accept(File dir, String s)
1932 /** The version of this package */
1933 final static public String version()
1935 return "lgpl release 1.5.3";
1939 * Once this method is called, the state of variables ignoreCase and
1940 * dontMatchInQuotes should not be changed as the results will be
1941 * unpredictable. However, search and matchAt will run more quickly. Note that
1942 * you can check to see if the pattern has been optimized by calling the
1943 * optimized() method.
1945 * This method will attempt to rewrite your pattern in a way that makes it
1946 * faster (not all patterns execute at the same speed). In general,
1947 * "(?: ... )" will be faster than "( ... )" so if you don't need the
1948 * backreference, you should group using the former pattern.
1950 * It will also introduce new pattern elements that you can't get to
1951 * otherwise, for example if you have a large table of strings, i.e. the
1952 * months of the year "(January|February|...)" optimize() will make a
1953 * Hashtable that takes it to the next appropriate pattern element --
1954 * eliminating the need for a linear search.
1956 * @see com.stevesoft.pat.Regex#optimized
1957 * @see com.stevesoft.pat.Regex#ignoreCase
1958 * @see com.stevesoft.pat.Regex#dontMatchInQuotes
1959 * @see com.stevesoft.pat.Regex#matchAt
1960 * @see com.stevesoft.pat.Regex#search
1962 public void optimize()
1964 if (optimized() || thePattern == null)
1968 minMatch = new patInt(0); // thePattern.countMinChars();
1969 thePattern = RegOpt.opt(thePattern, ignoreCase, dontMatchInQuotes);
1970 skipper = Skip.findSkip(this);
1971 // RegOpt.setParents(this);
1978 * This function returns true if the optimize method has been called.
1980 public boolean optimized()
1982 return minMatch != null;
1986 * A bit of syntactic surgar for those who want to make their code look more
1987 * perl-like. To use this initialize your Regex object by saying:
1990 * Regex r1 = Regex.perlCode("s/hello/goodbye/");
1991 * Regex r2 = Regex.perlCode("s'fish'frog'i");
1992 * Regex r3 = Regex.perlCode("m'hello');
1995 * The i for ignoreCase is supported in this syntax, as well as m, s, and x.
1996 * The g flat is a bit of a special case.
1998 * If you wish to replace all occurences of a pattern, you do not put a 'g' in
1999 * the perlCode, but call Regex's replaceAll method.
2001 * If you wish to simply and only do a search for r2's pattern, you can do
2002 * this by calling the searchFrom method method repeatedly, or by calling
2003 * search repeatedly if the g flag is set.
2005 * Note: Currently perlCode does <em>not</em> support the (?e=#) syntax for
2006 * changing the escape character.
2009 public static Regex perlCode(String s)
2011 // this file is big enough, see parsePerl.java
2012 // for this function.
2013 return parsePerl.parse(s);
2016 static final char back_slash = '\\';
2019 * Checks to see if there are only literal and no special pattern elements in
2022 public boolean isLiteral()
2024 Pattern x = thePattern;
2027 if (x instanceof oneChar)
2031 else if (x instanceof Skipped)
2045 * You only need to know about this if you are inventing your own pattern
2048 public patInt countMinChars()
2050 return thePattern.countMinChars();
2054 * You only need to know about this if you are inventing your own pattern
2057 public patInt countMaxChars()
2059 return thePattern.countMaxChars();
2062 boolean isHexDigit(StrPos sp)
2066 && ((sp.c >= '0' && sp.c <= '9')
2067 || (sp.c >= 'a' && sp.c <= 'f') || (sp.c >= 'A' && sp.c <= 'F'));
2071 boolean isOctalDigit(StrPos sp, boolean first)
2073 boolean r = !sp.eos && !(first ^ sp.dontMatch) && sp.c >= '0'
2078 int getHexDigit(StrPos sp)
2080 if (sp.c >= '0' && sp.c <= '9')
2084 if (sp.c >= 'a' && sp.c <= 'f')
2086 return sp.c - 'a' + 10;
2088 return sp.c - 'A' + 10;
2091 boolean next2Hex(StrPos sp)
2093 StrPos sp2 = new StrPos(sp);
2095 if (!isHexDigit(sp2))
2100 if (!isHexDigit(sp2))
2107 boolean isOctalString(StrPos sp)
2109 if (!isOctalDigit(sp, true))
2113 StrPos sp2 = new StrPos(sp);
2115 if (!isOctalDigit(sp2, false))