1 4 package com.openedit.archive.cumulus; 5 6 7 41 import java.util.*; 42 import java.util.regex.Matcher ; 43 import java.util.regex.Pattern ; 44 45 47 63 public class Parser { 64 65 public static void main(String [] args) { 66 Parser parser = new Parser(); 67 List list = parser.parse( 68 "\"LU\",86.25,\"11/4/1998\",\"2:19PM\",+4.0625"); 69 Iterator it = list.iterator(); 70 while (it.hasNext()) { 71 System.out.println(it.next()); 72 } 73 74 parser = new Parser('|'); 76 list = parser.parse( 77 "\"LU\"|86.25|\"11/4/1998\"|\"2:19PM\"|+4.0625"); 78 it = list.iterator(); 79 while (it.hasNext()) { 80 System.out.println(it.next()); 81 } 82 } 83 84 85 public static final char DEFAULT_SEP = ','; 86 87 88 public Parser() { 89 this(DEFAULT_SEP); 90 } 91 92 96 public Parser(char sep) { 97 fieldSep = sep; 98 } 99 100 101 protected List list = new ArrayList(); 102 protected Pattern tabs = Pattern.compile("\t"); 103 104 105 protected char fieldSep; 106 107 108 public String [] parseRegEx(String line) 109 { 110 String [] args = tabs.split(line); 112 return args; 114 } 115 116 120 public List parse(String line) 121 { 122 StringBuffer sb = new StringBuffer (); 123 list.clear(); int i = 0; 125 126 if (line.length() == 0) { 127 list.add(line); 128 return list; 129 } 130 131 do { 132 sb.setLength(0); 133 if (i < line.length() && line.charAt(i) == '"') 134 i = advQuoted(line, sb, ++i); else 136 i = advPlain(line, sb, i); 137 list.add(sb.toString()); 138 i++; 139 } while (i < line.length()); 140 141 return list; 142 } 143 144 145 protected int advQuoted(String s, StringBuffer sb, int i) 146 { 147 int j; 148 int len= s.length(); 149 for (j=i; j<len; j++) { 150 if (s.charAt(j) == '"' && j+1 < len) { 151 if (s.charAt(j+1) == '"') { 152 j++; } else if (s.charAt(j+1) == fieldSep) { j++; break; 156 } 157 } else if (s.charAt(j) == '"' && j+1 == len) { break; } 160 sb.append(s.charAt(j)); } 162 return j; 163 } 164 165 166 protected int advPlain(String s, StringBuffer sb, int i) 167 { 168 int j; 169 170 j = s.indexOf(fieldSep, i); if (j == -1) { sb.append(s.substring(i)); 173 return s.length(); 174 } else { 175 sb.append(s.substring(i, j)); 176 return j; 177 } 178 } 179 } 180 181 | Popular Tags |