View Javadoc
1   package io.guixer.logs;
2   
3   import static com.google.common.base.Preconditions.checkNotNull;
4   import static com.google.common.collect.Lists.newArrayList;
5   
6   import java.util.List;
7   
8   import com.google.common.collect.Iterables;
9   
10  public abstract class Utils {
11  
12  	public static String[] tokenize(
13  		final String s
14  	) {
15  
16  		checkNotNull(s, "s");
17  
18  		final List<String> tokens = newArrayList();
19  
20  		final StringBuilder sb = new StringBuilder();
21  
22  		final char[] charArray = s.toCharArray();
23  
24  		boolean inDoubleQuotes = false;
25  
26  		for (int i = 0; i < charArray.length; ++i) {
27  
28  			final char c = charArray[i];
29  
30  			if (c == ' ') {
31  
32  				if (sb.isEmpty()) {
33  
34  					continue;
35  				}
36  
37  				if (inDoubleQuotes) {
38  
39  					sb.append(c); // "aa[ ]bb"
40  
41  				} else {
42  
43  					tokens.add(sb.toString());
44  
45  					sb.setLength(0); // aa[ ]bb
46  				}
47  
48  			} else if (c == '"') {
49  
50  				if (inDoubleQuotes) {
51  
52  					tokens.add(sb.toString()); // "aabb["]
53  
54  					inDoubleQuotes = false;
55  
56  					sb.setLength(0);
57  
58  				} else if (sb.isEmpty()) {
59  
60  					inDoubleQuotes = true; // ["]aabb"
61  
62  				} else {
63  
64  					sb.append(c); // aa["]bb
65  				}
66  
67  			} else if (c == '\\') {
68  
69  				++i;
70  
71  				final char c2 = charArray[i];
72  
73  				sb.append(c2);
74  
75  			} else {
76  
77  				sb.append(c); // aa[b]cc
78  			}
79  		}
80  
81  		if (!sb.isEmpty()) {
82  
83  			tokens.add(sb.toString());
84  		}
85  
86  		return Iterables.toArray(tokens, String.class);
87  	}
88  }