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
312 * BackRefOffset gives the identity number of the first pattern. Version 1.0
313 * used zero, version 1.1 uses 1 to be more compatible with perl.
315 static int BackRefOffset = 1;
317 private static Pattern none = new NoPattern();
319 Pattern thePattern = none;
321 patInt minMatch = new patInt(0);
323 static Hashtable validators = new Hashtable();
326 define("p", "(?>1)", new UnicodePunct());
327 define("P", "(?>1)", new NUnicodePunct());
328 define("s", "(?>1)", new UnicodeWhite());
329 define("S", "(?>1)", new NUnicodeWhite());
330 define("w", "(?>1)", new UnicodeW());
331 define("W", "(?>1)", new NUnicodeW());
332 define("d", "(?>1)", new UnicodeDigit());
333 define("D", "(?>1)", new NUnicodeDigit());
334 define("m", "(?>1)", new UnicodeMath());
335 define("M", "(?>1)", new NUnicodeMath());
336 define("c", "(?>1)", new UnicodeCurrency());
337 define("C", "(?>1)", new NUnicodeCurrency());
338 define("a", "(?>1)", new UnicodeAlpha());
339 define("A", "(?>1)", new NUnicodeAlpha());
340 define("uc", "(?>1)", new UnicodeUpper());
341 define("lc", "(?>1)", new UnicodeLower());
344 /** Set the dontMatch in quotes flag. */
345 public void setDontMatchInQuotes(boolean b)
347 dontMatchInQuotes = b;
350 /** Find out if the dontMatchInQuotes flag is enabled. */
351 public boolean getDontMatchInQuotes()
353 return dontMatchInQuotes;
356 boolean dontMatchInQuotes = false;
359 * Set the state of the ignoreCase flag. If set to true, then the pattern
360 * matcher will ignore case when searching for a match.
362 public void setIgnoreCase(boolean b)
368 * Get the state of the ignoreCase flag. Returns true if we are ignoring the
369 * case of the pattern, false otherwise.
371 public boolean getIgnoreCase()
376 boolean ignoreCase = false;
378 static boolean defaultMFlag = false;
381 * Set the default value of the m flag. If it is set to true, then the MFlag
382 * will be on for any regex search executed.
384 public static void setDefaultMFlag(boolean mFlag)
386 defaultMFlag = mFlag;
390 * Get 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 boolean getDefaultMFlag()
399 * Initializes the object without a Pattern. To supply a Pattern use
402 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
409 * Create and compile a Regex, but do not throw any exceptions. If you wish to
410 * have exceptions thrown for syntax errors, you must use the Regex(void)
411 * constructor to create the Regex object, and then call the compile method.
412 * Therefore, you should only call this method when you know your pattern is
413 * right. I will probably become more like
415 * @see com.stevesoft.pat.Regex#search(java.lang.String)
416 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
418 public Regex(String s)
423 } catch (RegSyntax rs)
428 ReplaceRule rep = null;
431 * Create and compile both a Regex and a ReplaceRule.
433 * @see com.stevesoft.pat.ReplaceRule
434 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
436 public Regex(String s, String rp)
439 rep = ReplaceRule.perlCode(rp);
443 * Create and compile a Regex, but give it the ReplaceRule specified. This
444 * allows the user finer control of the Replacement process, if that is
447 * @see com.stevesoft.pat.ReplaceRule
448 * @see com.stevesoft.pat.Regex#compile(java.lang.String)
450 public Regex(String s, ReplaceRule rp)
457 * Change the ReplaceRule of this Regex by compiling a new one using String
460 public void setReplaceRule(String rp)
462 rep = ReplaceRule.perlCode(rp);
463 repr = null; // Clear Replacer history
466 /** Change the ReplaceRule of this Regex to rp. */
467 public void setReplaceRule(ReplaceRule rp)
473 * Test to see if a custom defined rule exists.
475 * @see com.stevesoft.pat#define(java.lang.String,java.lang.String,Validator)
477 public static boolean isDefined(String nm)
479 return validators.get(nm) != null;
483 * Removes a custom defined rule.
485 * @see com.stevesoft.pat#define(java.lang.String,java.lang.String,Validator)
487 public static void undefine(String nm)
489 validators.remove(nm);
493 * Defines a method to create a new rule. See test/deriv2.java and
494 * test/deriv3.java for examples of how to use it.
496 public static void define(String nm, String pat, Validator v)
499 validators.put(nm, v);
503 * Defines a shorthand for a pattern. The pattern will be invoked by a string
504 * that has the form "(??"+nm+")".
506 public static void define(String nm, String pat)
508 validators.put(nm, pat);
511 /** Get the current ReplaceRule. */
512 public ReplaceRule getReplaceRule()
517 Replacer repr = null;
519 final Replacer _getReplacer()
521 return repr == null ? repr = new Replacer() : repr;
524 public Replacer getReplacer()
528 repr = new Replacer();
536 * Replace the first occurence of this pattern in String s according to the
539 * @see com.stevesoft.pat.ReplaceRule
540 * @see com.stevesoft.pat.Regex#getReplaceRule()
542 public String replaceFirst(String s)
544 return _getReplacer().replaceFirstRegion(s, this, 0, s.length())
549 * Replace the first occurence of this pattern in String s beginning with
550 * position pos according to the ReplaceRule.
552 * @see com.stevesoft.pat.ReplaceRule
553 * @see com.stevesoft.pat.Regex#getReplaceRule()
555 public String replaceFirstFrom(String s, int pos)
557 return _getReplacer().replaceFirstRegion(s, this, pos, s.length())
562 * Replace the first occurence of this pattern in String s beginning with
563 * position start and ending with end according to the ReplaceRule.
565 * @see com.stevesoft.pat.ReplaceRule
566 * @see com.stevesoft.pat.Regex#getReplaceRule()
568 public String replaceFirstRegion(String s, int start, int end)
570 return _getReplacer().replaceFirstRegion(s, this, start, end)
575 * Replace all occurences of this pattern in String s according to the
578 * @see com.stevesoft.pat.ReplaceRule
579 * @see com.stevesoft.pat.Regex#getReplaceRule()
581 public String replaceAll(String s)
583 return _getReplacer().replaceAllRegion(s, this, 0, s.length())
587 public StringLike replaceAll(StringLike s)
589 return _getReplacer().replaceAllRegion(s, this, 0, s.length());
593 * Replace all occurences of this pattern in String s beginning with position
594 * pos according to the ReplaceRule.
596 * @see com.stevesoft.pat.ReplaceRule
597 * @see com.stevesoft.pat.Regex#getReplaceRule()
599 public String replaceAllFrom(String s, int pos)
601 return _getReplacer().replaceAllRegion(s, this, pos, s.length())
606 * Replace all occurences of this pattern in String s beginning with position
607 * start and ending with end according to the ReplaceRule.
609 * @see com.stevesoft.pat.ReplaceRule
610 * @see com.stevesoft.pat.Regex#getReplaceRule()
612 public String replaceAllRegion(String s, int start, int end)
614 return _getReplacer().replaceAllRegion(s, this, start, end).toString();
617 /** Essentially clones the Regex object */
618 public Regex(Regex r)
621 dontMatchInQuotes = r.dontMatchInQuotes;
623 ignoreCase = r.ignoreCase;
631 rep = (ReplaceRule) r.rep.clone();
634 * try { compile(r.toString()); } catch(RegSyntax r_) {}
636 thePattern = r.thePattern.clone(new Hashtable());
637 minMatch = r.minMatch;
642 * By default, the escape character is the backslash, but you can make it
643 * anything you want by setting this variable.
645 public char esc = Pattern.ESC;
648 * This method compiles a regular expression, making it possible to call the
649 * search or matchAt methods.
651 * @exception com.stevesoft.pat.RegSyntax
652 * is thrown if a syntax error is encountered in the pattern. For
653 * example, "x{3,1}" or "*a" are not valid patterns.
654 * @see com.stevesoft.pat.Regex#search
655 * @see com.stevesoft.pat.Regex#matchAt
657 public void compile(String prepat) throws RegSyntax
659 String postpat = parsePerl.codify(prepat, true);
660 String pat = postpat == null ? prepat : postpat;
663 dontMatchInQuotes = false;
664 Rthings mk = new Rthings(this);
670 minMatch = new patInt(0);
671 StrPos sp = new StrPos(pat, 0);
672 if (sp.incMatch("(?e="))
678 newpat = reEscape(pat.substring(6), newEsc, Pattern.ESC);
681 else if (esc != Pattern.ESC)
683 newpat = reEscape(pat, esc, Pattern.ESC);
685 thePattern = _compile(newpat, mk);
686 numSubs_ = mk.val - offset;
691 * If a Regex is compared against a Regex, a check is done to see that the
692 * patterns are equal as well as the most recent match. If a Regex is compare
693 * with a RegRes, only the result of the most recent match is compared.
696 public boolean equals(Object o)
698 if (o instanceof Regex)
700 if (toString().equals(o.toString()))
702 return super.equals(o);
711 return super.equals(o);
715 /** A clone by any other name would smell as sweet. */
717 public Object clone()
719 return new Regex(this);
722 /** Return a clone of the underlying RegRes object. */
723 public RegRes result()
725 return (RegRes) super.clone();
728 // prep sets global variables of class
729 // Pattern so that it can access them
730 // during an attempt at a match
731 Pthings pt = new Pthings();
733 final Pthings prep(StringLike s)
736 pt.lastPos = matchedTo();
741 if ((s == null ? null : s.unwrap()) != (src == null ? null : s.unwrap()))
746 pt.dotDoesntMatchCR = dotDoesntMatchCR && (!sFlag);
747 pt.mFlag = (mFlag | defaultMFlag);
748 pt.ignoreCase = ignoreCase;
750 if (pt.marks != null)
752 for (int i = 0; i < pt.marks.length; i++)
758 pt.nMarks = numSubs_;
760 if (dontMatchInQuotes)
772 * Attempt to match a Pattern beginning at a specified location within the
775 * @see com.stevesoft.pat.Regex#search
777 public boolean matchAt(String s, int start_pos)
779 return _search(s, start_pos, start_pos);
783 * Attempt to match a Pattern beginning at a specified location within the
786 * @see com.stevesoft.pat.Regex#search
788 public boolean matchAt(StringLike s, int start_pos)
790 return _search(s, start_pos, start_pos);
794 * Search through a String for the first occurrence of a match.
796 * @see com.stevesoft.pat.Regex#searchFrom
797 * @see com.stevesoft.pat.Regex#matchAt
799 public boolean search(String s)
803 throw new NullPointerException(
805 .getString("exception.null_string_given_to_regex_search"));
807 return _search(s, 0, s.length());
810 public boolean search(StringLike sl)
814 throw new NullPointerException(
816 .getString("exception.null_string_like_given_to_regex_search"));
818 return _search(sl, 0, sl.length());
821 public boolean reverseSearch(String s)
825 throw new NullPointerException(
827 .getString("exception.null_string_given_to_regex_reverse_search"));
829 return _reverseSearch(s, 0, s.length());
832 public boolean reverseSearch(StringLike sl)
836 throw new NullPointerException(
838 .getString("exception.null_string_like_given_to_regex_reverse_search"));
840 return _reverseSearch(sl, 0, sl.length());
844 * Search through a String for the first occurence of a match, but start at
851 public boolean searchFrom(String s, int start)
855 throw new NullPointerException(
857 .getString("exception.null_string_like_given_to_regex_search_from"));
859 return _search(s, start, s.length());
862 public boolean searchFrom(StringLike s, int start)
866 throw new NullPointerException(
868 .getString("exception.null_string_like_given_to_regex_search_from"));
870 return _search(s, start, s.length());
874 * Search through a region of a String for the first occurence of a match.
876 public boolean searchRegion(String s, int start, int end)
880 throw new NullPointerException(
882 .getString("exception.null_string_like_given_to_regex_search_region"));
884 return _search(s, start, end);
888 * Set this to change the default behavior of the "." pattern. By default it
889 * now matches perl's behavior and fails to match the '\n' character.
891 public static boolean dotDoesntMatchCR = true;
897 boolean gFlag = false;
899 /** Set the 'g' flag */
900 public void setGFlag(boolean b)
905 /** Get the state of the 'g' flag. */
906 public boolean getGFlag()
911 boolean sFlag = false;
913 /** Get the state of the sFlag */
914 public boolean getSFlag()
919 boolean mFlag = false;
921 /** Get the state of the sFlag */
922 public boolean getMFlag()
927 final boolean _search(String s, int start, int end)
929 return _search(new StringWrap(s), start, end);
932 final boolean _search(StringLike s, int start, int end)
934 if (gFlag && gFlagto > 0 && gFlags != null
935 && s.unwrap() == gFlags.unwrap())
941 Pthings pt = prep(s);
943 int up = (minMatch == null ? end : end - minMatch.i);
945 if (up < start && end >= start)
952 for (int i = start; i <= up; i++)
954 charsMatched_ = thePattern.matchAt(s, i, pt);
955 if (charsMatched_ >= 0)
957 matchFrom_ = thePattern.mfrom;
959 gFlagto = matchFrom_ + charsMatched_;
961 return didMatch_ = true;
968 for (int i = start; i <= up; i++)
970 i = skipper.find(src, i, up);
973 charsMatched_ = matchFrom_ = -1;
974 return didMatch_ = false;
976 charsMatched_ = thePattern.matchAt(s, i, pt);
977 if (charsMatched_ >= 0)
979 matchFrom_ = thePattern.mfrom;
981 gFlagto = matchFrom_ + charsMatched_;
983 return didMatch_ = true;
987 return didMatch_ = false;
991 * final boolean _search(LongStringLike s,long start,long end) { if(gFlag &&
992 * gFlagto > 0 && s==gFlags) start = gFlagto; gFlags = null;
994 * Pthings pt=prep(s);
996 * int up = end;//(minMatch == null ? end : end-minMatch.i);
998 * if(up < start && end >= start) up = start;
1000 * if(skipper == null) { for(long i=start;i<=up;i++) { charsMatched_ =
1001 * thePattern.matchAt(s,i,pt); if(charsMatched_ >= 0) { matchFrom_ =
1002 * thePattern.mfrom; marks = pt.marks; gFlagto = matchFrom_+charsMatched_;
1003 * return didMatch_=true; } } } else { pt.no_check = true; for(long
1004 * i=start;i<=up;i++) { i = skipper.find(src,i,up); if(i<0) { charsMatched_ =
1005 * matchFrom_ = -1; return didMatch_ = false; } charsMatched_ =
1006 * thePattern.matchAt(s,i,pt); if(charsMatched_ >= 0) { matchFrom_ =
1007 * thePattern.mfrom; marks = pt.marks; gFlagto = matchFrom_+charsMatched_;
1008 * gFlags = s; return didMatch_=true; } else { i = s.adjustIndex(i); up =
1009 * s.adjustEnd(i); } } } return didMatch_=false; }
1012 boolean _reverseSearch(String s, int start, int end)
1014 return _reverseSearch(new StringWrap(s), start, end);
1017 boolean _reverseSearch(StringLike s, int start, int end)
1019 if (gFlag && gFlagto > 0 && s.unwrap() == gFlags.unwrap())
1024 Pthings pt = prep(s);
1025 for (int i = end; i >= start; i--)
1027 charsMatched_ = thePattern.matchAt(s, i, pt);
1028 if (charsMatched_ >= 0)
1030 matchFrom_ = thePattern.mfrom;
1032 gFlagto = matchFrom_ - 1;
1034 return didMatch_ = true;
1037 return didMatch_ = false;
1040 // This routine sets the cbits variable
1041 // of class Pattern. Cbits is true for
1042 // the bit corresponding to a character inside
1044 static StringLike lasts = null;
1046 static BitSet lastbs = null;
1048 static void setCbits(StringLike s, Pthings pt)
1055 BitSet bs = new BitSet(s.length());
1057 boolean setBit = false;
1058 for (int i = 0; i < s.length(); i++)
1064 char c = s.charAt(i);
1065 if (!setBit && c == '"')
1071 else if (!setBit && c == '\'')
1077 else if (setBit && c == qc)
1081 else if (setBit && c == '\\' && i + 1 < s.length())
1090 pt.cbits = lastbs = bs;
1094 // Wanted user to over-ride this in alpha version,
1095 // but it wasn't really necessary because of this trick:
1100 return getClass().newInstance();
1101 } catch (InstantiationException ie)
1104 } catch (IllegalAccessException iae)
1111 * Only needed for creating your own extensions of Regex. This method adds the
1112 * next Pattern in the chain of patterns or sets the Pattern if it is the
1115 protected void add(Pattern p2)
1129 * You only need to use this method if you are creating your own extentions to
1130 * Regex. compile1 compiles one Pattern element, it can be over-ridden to
1131 * allow the Regex compiler to understand new syntax. See deriv.java for an
1132 * example. This routine is the heart of class Regex. Rthings has one integer
1133 * member called intValue, it is used to keep track of the number of ()'s in
1136 * @exception com.stevesoft.pat.RegSyntax
1137 * is thrown when a nonsensensical pattern is supplied. For
1138 * example, a pattern beginning with *.
1140 protected void compile1(StrPos sp, Rthings mk) throws RegSyntax
1145 add(matchBracket(sp));
1147 else if (sp.match('|'))
1155 p = new NullPattern();
1160 else if (sp.incMatch("(?<"))
1162 patInt i = sp.getPatInt();
1165 RegSyntaxError.endItAll("No int after (?<");
1167 add(new Backup(i.intValue()));
1170 RegSyntaxError.endItAll("No ) after (?<");
1173 else if (sp.incMatch("(?>"))
1175 patInt i = sp.getPatInt();
1178 RegSyntaxError.endItAll("No int after (?>");
1180 add(new Backup(-i.intValue()));
1183 RegSyntaxError.endItAll("No ) after (?<");
1186 else if (sp.incMatch("(?@"))
1194 RegSyntaxError.endItAll("(?@ does not have closing paren");
1196 add(new Group(op, cl));
1198 else if (sp.incMatch("(?#"))
1200 while (!sp.match(')'))
1205 else if (sp.dontMatch && sp.c == 'w')
1207 // Regex r = new Regex();
1208 // r._compile("[a-zA-Z0-9_]",mk);
1209 // add(new Goop("\\w",r.thePattern));
1210 Bracket b = new Bracket(false);
1211 b.addOr(new Range('a', 'z'));
1212 b.addOr(new Range('A', 'Z'));
1213 b.addOr(new Range('0', '9'));
1214 b.addOr(new oneChar('_'));
1217 else if (sp.dontMatch && sp.c == 'G')
1221 else if (sp.dontMatch && sp.c == 's')
1223 // Regex r = new Regex();
1224 // r._compile("[ \t\n\r\b]",mk);
1225 // add(new Goop("\\s",r.thePattern));
1226 Bracket b = new Bracket(false);
1227 b.addOr(new oneChar((char) 32));
1228 b.addOr(new Range((char) 8, (char) 10));
1229 b.addOr(new oneChar((char) 13));
1232 else if (sp.dontMatch && sp.c == 'd')
1234 // Regex r = new Regex();
1235 // r._compile("[0-9]",mk);
1236 // add(new Goop("\\d",r.thePattern));
1237 Range digit = new Range('0', '9');
1238 digit.printBrackets = true;
1241 else if (sp.dontMatch && sp.c == 'W')
1243 // Regex r = new Regex();
1244 // r._compile("[^a-zA-Z0-9_]",mk);
1245 // add(new Goop("\\W",r.thePattern));
1246 Bracket b = new Bracket(true);
1247 b.addOr(new Range('a', 'z'));
1248 b.addOr(new Range('A', 'Z'));
1249 b.addOr(new Range('0', '9'));
1250 b.addOr(new oneChar('_'));
1253 else if (sp.dontMatch && sp.c == 'S')
1255 // Regex r = new Regex();
1256 // r._compile("[^ \t\n\r\b]",mk);
1257 // add(new Goop("\\S",r.thePattern));
1258 Bracket b = new Bracket(true);
1259 b.addOr(new oneChar((char) 32));
1260 b.addOr(new Range((char) 8, (char) 10));
1261 b.addOr(new oneChar((char) 13));
1264 else if (sp.dontMatch && sp.c == 'D')
1266 // Regex r = new Regex();
1267 // r._compile("[^0-9]",mk);
1268 // add(new Goop("\\D",r.thePattern));
1269 Bracket b = new Bracket(true);
1270 b.addOr(new Range('0', '9'));
1273 else if (sp.dontMatch && sp.c == 'B')
1275 Regex r = new Regex();
1276 r._compile("(?!" + back_slash + "b)", mk);
1279 else if (isOctalString(sp))
1283 d = 8 * d + sp.c - '0';
1284 StrPos sp2 = new StrPos(sp);
1286 if (isOctalDigit(sp2, false))
1289 d = 8 * d + sp.c - '0';
1291 add(new oneChar((char) d));
1293 else if (sp.dontMatch && sp.c >= '1' && sp.c <= '9')
1295 int iv = sp.c - '0';
1296 StrPos s2 = new StrPos(sp);
1298 if (!s2.dontMatch && s2.c >= '0' && s2.c <= '9')
1300 iv = 10 * iv + (s2.c - '0');
1303 add(new BackMatch(iv));
1305 else if (sp.dontMatch && sp.c == 'b')
1307 add(new Boundary());
1309 else if (sp.match('\b'))
1311 add(new Boundary());
1313 else if (sp.match('$'))
1317 else if (sp.dontMatch && sp.c == 'Z')
1319 add(new End(false));
1321 else if (sp.match('.'))
1325 else if (sp.incMatch("(??"))
1327 StringBuffer sb = new StringBuffer();
1328 StringBuffer sb2 = new StringBuffer();
1329 while (!sp.match(')') && !sp.match(':'))
1334 if (sp.incMatch(":"))
1336 while (!sp.match(')'))
1342 String sbs = sb.toString();
1343 if (validators.get(sbs) instanceof String)
1345 String pat = (String) validators.get(sbs);
1346 Regex r = newRegex();
1347 Rthings rth = new Rthings(this);
1348 rth.noBackRefs = true;
1349 r._compile(pat, rth);
1354 Custom cm = new Custom(sb.toString());
1357 Validator v2 = cm.v.arg(sb2.toString());
1360 v2.argsave = sb2.toString();
1361 String p = cm.v.pattern;
1365 Regex r = newRegex();
1366 Rthings rth = new Rthings(this);
1367 rth.noBackRefs = true;
1368 r._compile(cm.v.pattern, rth);
1369 cm.sub = r.thePattern;
1370 cm.sub.add(new CustomEndpoint(cm));
1371 cm.sub.setParent(cm);
1376 else if (sp.match('('))
1379 Regex r = newRegex();
1382 if (sp.incMatch("?:"))
1386 else if (sp.incMatch("?="))
1388 r.or = new lookAhead(false);
1390 else if (sp.incMatch("?!"))
1392 r.or = new lookAhead(true);
1394 else if (sp.match('?'))
1401 mk.ignoreCase = true;
1405 mk.dontMatchInQuotes = true;
1409 mk.optimizeMe = true;
1424 } while (!sp.match(')') && !sp.eos);
1427 if (sp.eos) // throw new RegSyntax
1429 RegSyntaxError.endItAll("Unclosed ()");
1433 { // just ordinary parenthesis
1434 r.or = mk.noBackRefs ? new Or() : new OrMark(mk.val++);
1438 add(r._compile(sp, mk));
1441 else if (sp.match('^'))
1443 add(new Start(true));
1445 else if (sp.dontMatch && sp.c == 'A')
1447 add(new Start(false));
1449 else if (sp.match('*'))
1451 addMulti(new patInt(0), new patInf());
1453 else if (sp.match('+'))
1455 addMulti(new patInt(1), new patInf());
1457 else if (sp.match('?'))
1459 addMulti(new patInt(0), new patInt(1));
1461 else if (sp.match('{'))
1463 boolean bad = false;
1464 StrPos sp2 = new StrPos(sp);
1465 // StringBuffer sb = new StringBuffer();
1467 patInt i1 = sp.getPatInt();
1478 * RegSyntaxError.endItAll( "String \"{"+i2+ "\" should be followed
1490 i2 = sp.getPatInt();
1493 if (i1 == null || i2 == null)
1496 * throw new RegSyntax("Badly formatted Multi: " +"{"+i1+","+i2+"}");
1503 add(new oneChar(sp.c));
1510 else if (sp.escMatch('x') && next2Hex(sp))
1513 int d = getHexDigit(sp);
1515 d = 16 * d + getHexDigit(sp);
1516 add(new oneChar((char) d));
1518 else if (sp.escMatch('c'))
1521 if (sp.c < Ctrl.cmap.length)
1523 add(new oneChar(Ctrl.cmap[sp.c]));
1527 add(new oneChar(sp.c));
1530 else if (sp.escMatch('f'))
1532 add(new oneChar((char) 12));
1534 else if (sp.escMatch('a'))
1536 add(new oneChar((char) 7));
1538 else if (sp.escMatch('t'))
1540 add(new oneChar('\t'));
1542 else if (sp.escMatch('n'))
1544 add(new oneChar('\n'));
1546 else if (sp.escMatch('r'))
1548 add(new oneChar('\r'));
1550 else if (sp.escMatch('b'))
1552 add(new oneChar('\b'));
1554 else if (sp.escMatch('e'))
1556 add(new oneChar((char) 27));
1560 add(new oneChar(sp.c));
1563 RegSyntaxError.endItAll("Unmatched right paren in pattern");
1568 // compiles all Pattern elements, internal method
1569 private Pattern _compile(String pat, Rthings mk) throws RegSyntax
1572 sFlag = mFlag = ignoreCase = gFlag = false;
1573 StrPos sp = new StrPos(pat, 0);
1574 thePattern = _compile(sp, mk);
1583 Pattern _compile(StrPos sp, Rthings mk) throws RegSyntax
1585 while (!(sp.eos || (or != null && sp.match(')'))))
1594 else if (sp.eos && mk.parenLevel != 0)
1596 RegSyntaxError.endItAll("Unclosed Parenthesis! lvl=" + mk.parenLevel);
1602 p = new NullPattern();
1607 return p == null ? new NullPattern() : p;
1610 // add a multi object to the end of the chain
1611 // which applies to the last object
1612 void addMulti(patInt i1, patInt i2) throws RegSyntax
1614 Pattern last, last2;
1615 for (last = p; last != null && last.next != null; last = last.next)
1619 if (last == null || last == p)
1625 for (last2 = p; last2.next != last; last2 = last2.next)
1630 if (last instanceof Multi && i1.intValue() == 0 && i2.intValue() == 1)
1632 ((Multi) last).matchFewest = true;
1634 else if (last instanceof FastMulti && i1.intValue() == 0
1635 && i2.intValue() == 1)
1637 ((FastMulti) last).matchFewest = true;
1639 else if (last instanceof DotMulti && i1.intValue() == 0
1640 && i2.intValue() == 1)
1642 ((DotMulti) last).matchFewest = true;
1644 else if (last instanceof Multi || last instanceof DotMulti
1645 || last instanceof FastMulti)
1647 throw new RegSyntax("Syntax error.");
1649 else if (last2 == null)
1651 p = mkMulti(i1, i2, p);
1655 last2.next = mkMulti(i1, i2, last);
1659 final static Pattern mkMulti(patInt lo, patInt hi, Pattern p)
1662 if (p instanceof Any && p.next == null)
1664 return new DotMulti(lo, hi);
1666 return RegOpt.safe4fm(p) ? (Pattern) new FastMulti(lo, hi, p)
1667 : (Pattern) new Multi(lo, hi, p);
1670 // process the bracket operator
1671 Pattern matchBracket(StrPos sp) throws RegSyntax
1676 ret = new Bracket(true);
1681 ret = new Bracket(false);
1685 // throw new RegSyntax
1686 RegSyntaxError.endItAll("Unmatched []");
1689 while (!sp.eos && !sp.match(']'))
1691 StrPos s1 = new StrPos(sp);
1693 StrPos s1_ = new StrPos(s1);
1695 if (s1.match('-') && !s1_.match(']'))
1697 StrPos s2 = new StrPos(s1);
1701 ret.addOr(new Range(sp.c, s2.c));
1706 else if (sp.escMatch('Q'))
1709 while (!sp.escMatch('E'))
1711 ret.addOr(new oneChar(sp.c));
1715 else if (sp.escMatch('d'))
1717 ret.addOr(new Range('0', '9'));
1719 else if (sp.escMatch('s'))
1721 ret.addOr(new oneChar((char) 32));
1722 ret.addOr(new Range((char) 8, (char) 10));
1723 ret.addOr(new oneChar((char) 13));
1725 else if (sp.escMatch('w'))
1727 ret.addOr(new Range('a', 'z'));
1728 ret.addOr(new Range('A', 'Z'));
1729 ret.addOr(new Range('0', '9'));
1730 ret.addOr(new oneChar('_'));
1732 else if (sp.escMatch('D'))
1734 ret.addOr(new Range((char) 0, (char) 47));
1735 ret.addOr(new Range((char) 58, (char) 65535));
1737 else if (sp.escMatch('S'))
1739 ret.addOr(new Range((char) 0, (char) 7));
1740 ret.addOr(new Range((char) 11, (char) 12));
1741 ret.addOr(new Range((char) 14, (char) 31));
1742 ret.addOr(new Range((char) 33, (char) 65535));
1744 else if (sp.escMatch('W'))
1746 ret.addOr(new Range((char) 0, (char) 64));
1747 ret.addOr(new Range((char) 91, (char) 94));
1748 ret.addOr(new oneChar((char) 96));
1749 ret.addOr(new Range((char) 123, (char) 65535));
1751 else if (sp.escMatch('x') && next2Hex(sp))
1754 int d = getHexDigit(sp);
1756 d = 16 * d + getHexDigit(sp);
1757 ret.addOr(new oneChar((char) d));
1759 else if (sp.escMatch('a'))
1761 ret.addOr(new oneChar((char) 7));
1763 else if (sp.escMatch('f'))
1765 ret.addOr(new oneChar((char) 12));
1767 else if (sp.escMatch('e'))
1769 ret.addOr(new oneChar((char) 27));
1771 else if (sp.escMatch('n'))
1773 ret.addOr(new oneChar('\n'));
1775 else if (sp.escMatch('t'))
1777 ret.addOr(new oneChar('\t'));
1779 else if (sp.escMatch('r'))
1781 ret.addOr(new oneChar('\r'));
1783 else if (sp.escMatch('c'))
1786 if (sp.c < Ctrl.cmap.length)
1788 ret.addOr(new oneChar(Ctrl.cmap[sp.c]));
1792 ret.addOr(new oneChar(sp.c));
1795 else if (isOctalString(sp))
1799 d = 8 * d + sp.c - '0';
1800 StrPos sp2 = new StrPos(sp);
1802 if (isOctalDigit(sp2, false))
1805 d = 8 * d + sp.c - '0';
1807 ret.addOr(new oneChar((char) d));
1811 ret.addOr(new oneChar(sp.c));
1819 * Converts the stored Pattern to a String -- this is a decompile. Note that
1820 * \t and \n will really print out here, Not just the two character
1821 * representations. Also be prepared to see some strange output if your
1822 * characters are not printable.
1825 public String toString()
1827 if (false && thePattern == null)
1833 StringBuffer sb = new StringBuffer();
1834 if (esc != Pattern.ESC)
1840 if (gFlag || mFlag || !dotDoesntMatchCR || sFlag || ignoreCase
1841 || dontMatchInQuotes || optimized())
1852 if (sFlag || !dotDoesntMatchCR)
1856 if (dontMatchInQuotes)
1870 String patstr = thePattern.toString();
1871 if (esc != Pattern.ESC)
1873 patstr = reEscape(patstr, Pattern.ESC, esc);
1876 return sb.toString();
1880 // Re-escape Pattern, allows us to use a different escape
1882 static String reEscape(String s, char oldEsc, char newEsc)
1884 if (oldEsc == newEsc)
1889 StringBuffer sb = new StringBuffer();
1890 for (i = 0; i < s.length(); i++)
1892 if (s.charAt(i) == oldEsc && i + 1 < s.length())
1894 if (s.charAt(i + 1) == oldEsc)
1901 sb.append(s.charAt(i + 1));
1905 else if (s.charAt(i) == newEsc)
1912 sb.append(s.charAt(i));
1915 return sb.toString();
1919 * This method implements FilenameFilter, allowing one to use a Regex to
1920 * search through a directory using File.list. There is a FileRegex now that
1923 * @see com.stevesoft.pat.FileRegex
1926 public boolean accept(File dir, String s)
1931 /** The version of this package */
1932 final static public String version()
1934 return "lgpl release 1.5.3";
1938 * Once this method is called, the state of variables ignoreCase and
1939 * dontMatchInQuotes should not be changed as the results will be
1940 * unpredictable. However, search and matchAt will run more quickly. Note that
1941 * you can check to see if the pattern has been optimized by calling the
1942 * optimized() method.
1944 * This method will attempt to rewrite your pattern in a way that makes it
1945 * faster (not all patterns execute at the same speed). In general,
1946 * "(?: ... )" will be faster than "( ... )" so if you don't need the
1947 * backreference, you should group using the former pattern.
1949 * It will also introduce new pattern elements that you can't get to
1950 * otherwise, for example if you have a large table of strings, i.e. the
1951 * months of the year "(January|February|...)" optimize() will make a
1952 * Hashtable that takes it to the next appropriate pattern element --
1953 * eliminating the need for a linear search.
1955 * @see com.stevesoft.pat.Regex#optimized
1956 * @see com.stevesoft.pat.Regex#ignoreCase
1957 * @see com.stevesoft.pat.Regex#dontMatchInQuotes
1958 * @see com.stevesoft.pat.Regex#matchAt
1959 * @see com.stevesoft.pat.Regex#search
1961 public void optimize()
1963 if (optimized() || thePattern == null)
1967 minMatch = new patInt(0); // thePattern.countMinChars();
1968 thePattern = RegOpt.opt(thePattern, ignoreCase, dontMatchInQuotes);
1969 skipper = Skip.findSkip(this);
1970 // RegOpt.setParents(this);
1977 * This function returns true if the optimize method has been called.
1979 public boolean optimized()
1981 return minMatch != null;
1985 * A bit of syntactic surgar for those who want to make their code look more
1986 * perl-like. To use this initialize your Regex object by saying:
1989 * Regex r1 = Regex.perlCode("s/hello/goodbye/");
1990 * Regex r2 = Regex.perlCode("s'fish'frog'i");
1991 * Regex r3 = Regex.perlCode("m'hello');
1994 * The i for ignoreCase is supported in this syntax, as well as m, s, and x.
1995 * The g flat is a bit of a special case.
1997 * If you wish to replace all occurences of a pattern, you do not put a 'g' in
1998 * the perlCode, but call Regex's replaceAll method.
2000 * If you wish to simply and only do a search for r2's pattern, you can do
2001 * this by calling the searchFrom method method repeatedly, or by calling
2002 * search repeatedly if the g flag is set.
2004 * Note: Currently perlCode does <em>not</em> support the (?e=#) syntax for
2005 * changing the escape character.
2008 public static Regex perlCode(String s)
2010 // this file is big enough, see parsePerl.java
2011 // for this function.
2012 return parsePerl.parse(s);
2015 static final char back_slash = '\\';
2018 * Checks to see if there are only literal and no special pattern elements in
2021 public boolean isLiteral()
2023 Pattern x = thePattern;
2026 if (x instanceof oneChar)
2030 else if (x instanceof Skipped)
2044 * You only need to know about this if you are inventing your own pattern
2047 public patInt countMinChars()
2049 return thePattern.countMinChars();
2053 * You only need to know about this if you are inventing your own pattern
2056 public patInt countMaxChars()
2058 return thePattern.countMaxChars();
2061 boolean isHexDigit(StrPos sp)
2065 && ((sp.c >= '0' && sp.c <= '9')
2066 || (sp.c >= 'a' && sp.c <= 'f') || (sp.c >= 'A' && sp.c <= 'F'));
2070 boolean isOctalDigit(StrPos sp, boolean first)
2072 boolean r = !sp.eos && !(first ^ sp.dontMatch) && sp.c >= '0'
2077 int getHexDigit(StrPos sp)
2079 if (sp.c >= '0' && sp.c <= '9')
2083 if (sp.c >= 'a' && sp.c <= 'f')
2085 return sp.c - 'a' + 10;
2087 return sp.c - 'A' + 10;
2090 boolean next2Hex(StrPos sp)
2092 StrPos sp2 = new StrPos(sp);
2094 if (!isHexDigit(sp2))
2099 if (!isHexDigit(sp2))
2106 boolean isOctalString(StrPos sp)
2108 if (!isOctalDigit(sp, true))
2112 StrPos sp2 = new StrPos(sp);
2114 if (!isOctalDigit(sp2, false))