1 57 58 import org.apache.oro.text.regex.*; 59 60 75 public final class prefixExample { 76 public static final int REAL = 0; 77 public static final int INTEGER = 1; 78 public static final int STRING = 2; 79 80 public static final String [] types = { "Real", "Integer", "String" }; 81 public static final String whitespace = "\\s+"; 82 public static final String [] tokens = { 83 "-?\\d*\\.\\d+(?:[eE][-+]-?\\d+)?(?=\\s|$)", "-?\\d+(?=\\s|$)", "\\S+" 84 }; 85 public static final String tokens2 = 86 "(-?\\d*\\.\\d+(?:[eE][-+]-?\\d+)?(?=\\s|$))|(-?\\d+(?=\\s|$))|(\\S+)"; 87 88 public static final void main(String args[]) { 89 int token; 90 PatternMatcherInput input; 91 PatternMatcher matcher; 92 PatternCompiler compiler; 93 Pattern[] patterns; 94 Pattern tokenSeparator = null, patterns2 = null; 95 96 if(args.length < 1) { 97 System.err.println("Usage: prefixExample <sample input>"); 98 System.exit(1); 99 } 100 101 input = new PatternMatcherInput(args[0]); 102 compiler = new Perl5Compiler(); 103 patterns = new Pattern[tokens.length]; 104 105 try { 106 tokenSeparator = compiler.compile(whitespace); 107 patterns2 = compiler.compile(tokens2); 108 for(token=0; token < tokens.length; token++) 109 patterns[token] = compiler.compile(tokens[token]); 110 } catch(MalformedPatternException e) { 111 System.err.println("Bad pattern."); 112 e.printStackTrace(); 113 System.exit(1); 114 } 115 116 matcher = new Perl5Matcher(); 117 118 System.out.println("\nOne approach.\n"); 119 120 do { 121 for(token = 0; token < tokens.length; token++) 122 if(matcher.matchesPrefix(input, patterns[token])) { 123 System.out.println(types[token] + ": " + matcher.getMatch()); 124 break; 125 } 126 } while(matcher.contains(input, tokenSeparator)); 127 128 System.out.println("\nAn equivalent alternative.\n"); 132 133 input.setCurrentOffset(input.getBeginOffset()); 134 do { 135 if(matcher.matchesPrefix(input, patterns2)) { 136 MatchResult result = matcher.getMatch(); 137 138 for(token = 1; token <= tokens.length; token++) { 139 if(result.group(token) != null) { 140 System.out.println(types[token - 1] + ": " + result); 141 break; 142 } 143 } 144 } 145 } while(matcher.contains(input, tokenSeparator)); 146 147 } 148 } 149 | Popular Tags |