1 25 26 package net.yagga.util; 27 28 import java.util.StringTokenizer ; 29 import java.util.NoSuchElementException ; 30 31 32 39 40 public class StringQuoteTokenizer 41 { 42 private StringTokenizer st; 43 private boolean inQuote=false; 44 private String origDelim; 45 private int escapeType; 46 47 public static final int NO_ESCAPE=0; 48 public static final int ESCAPE_ALWAYS=1; 49 public static final int ESCAPE_IN_QUOTES=2; 50 51 public StringQuoteTokenizer(String str,String delim) 52 { 53 init(str,delim,NO_ESCAPE); 54 } 55 public StringQuoteTokenizer(String str,String delim, int escapeType) 56 { 57 init(str,delim,escapeType); 58 } 59 60 StringQuoteTokenizer(String str) 61 { 62 init(str," \t\n\r\f",NO_ESCAPE); 63 } 64 65 private void init(String str, String delim, int escape){ 66 st=new StringTokenizer (str,delim); 67 origDelim=delim; 68 escapeType=escape; 69 } 70 71 public boolean hasMoreElements(){ 72 return hasMoreTokens(); 73 } 74 75 public boolean hasMoreTokens(){ 76 return st.hasMoreTokens(); 77 } 78 79 public Object nextElement(){ 80 return (Object )nextToken(); 81 } 82 83 public String nextToken(){ 84 String token=st.nextToken(origDelim); 85 inQuote=false; 87 boolean quoted=false; 88 if(token.startsWith("\"")){ 89 inQuote=true; 91 quoted=true; 92 token=token.substring(1); 93 if(token.endsWith("\"") && !token.endsWith("\\\"")) 96 { 97 inQuote=false; 98 token=token.substring(0,token.length()-1); 99 } 100 } 101 String token2=token; 103 if(inQuote) 104 { 105 boolean ok=false; 107 while(!ok) 108 { 109 try 110 { 111 token2+=st.nextToken("\""); 112 if(!token2.endsWith("\\\"") || escapeType==NO_ESCAPE){ 114 ok=true; 115 st.nextToken(origDelim); 116 } 117 118 } 119 catch(NoSuchElementException e){ 120 break; 121 } 122 } 123 } 124 return token2; 125 } 126 127 128 public static void main(String [] argv){ 129 String test="12 sdf asdf \"opo opo opo \" sadf ' sdf s \"wererw\" 122 \"uno due\""; 130 System.out.println("'"+test+"'"); 131 StringQuoteTokenizer sqt=new StringQuoteTokenizer(test); 132 while(sqt.hasMoreTokens()){ 133 System.out.println("> '"+sqt.nextToken()+"'"); 134 } 135 } 136 } | Popular Tags |