-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenizer.java
More file actions
executable file
·82 lines (67 loc) · 1.73 KB
/
Tokenizer.java
File metadata and controls
executable file
·82 lines (67 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Tokenizer {
private class TokenInfo {
public final Pattern regex;
public final int token;
public TokenInfo(Pattern regex, int token) {
super();
this.regex = regex;
this.token = token;
}
}
public class Token {
public final int token;
public final String sequence;
public Token(int token, String sequence) {
super();
this.token = token;
this.sequence = sequence;
}
}
private LinkedList<TokenInfo> tokenInfos;
private LinkedList<Token> tokens;
public Tokenizer() {
tokenInfos = new LinkedList<TokenInfo>();
tokens = new LinkedList<Token>();
}
public void add(String regex, int token) {
tokenInfos
.add(new TokenInfo(Pattern.compile("^(" + regex + ")"), token));
}
public void tokenize(String str) {
String s = str.trim();
tokens.clear();
while (!s.equals("")) {
//System.out.println(s);
boolean match = false;
for (TokenInfo info : tokenInfos) {
Matcher m = info.regex.matcher(s);
if (m.find()) {
match = true;
String tok = m.group().trim();
s = m.replaceFirst("").trim();
tokens.add(new Token(info.token, tok));
break;
}
}
if (!match){
//throw new ParserException("Unexpected character in input: " + s);
tokens.clear();
System.out.println("Unexpected character in input: " + s);
return;
}
}
}
public LinkedList<Token> getTokens() {
return tokens;
}
public String getTokensString() {
StringBuilder sb = new StringBuilder();
for (Tokenizer.Token tok : tokens) {
sb.append(tok.token);
}
return sb.toString();
}
}