-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.hpp
82 lines (68 loc) · 2.1 KB
/
tokenizer.hpp
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
#ifndef _TOKENIZER_HPP_
#define _TOKENIZER_HPP_
#include <list>
#include <stdexcept>
#define ERR_SIZE 1000
namespace Tokenizer {
using namespace Tokenizer;
namespace {
bool isChar(char test) {
return ('a' <= test && test <= 'z') || ('A' <= test && test <= 'Z') || ('0' <= test && test <= '9');
}
bool isBoundary(char chr) {
return chr == '^' || chr == '$';
}
bool isBracket(char c) {
return c == '(' || c == ')' || c == ']' || c == '[';
}
bool isSymbol(char c) {
return c == '*' || c == '+' || c == '?';
}
};
enum Type {
CHARACTER,
BRACKET,
SYMBOL,
HYPHEN,
PIPE,
BOUNDARY,
WILDCARD
};
struct Token {
char character;
Type type;
Token(char character, Type type): character(character), type(type) {}
};
std::list<Token> tokenize(std::string& pattern) {
std::list<Token> tokens;
bool tochar = false;
for (char c: pattern) {
if (tochar) {
tokens.push_back(Token(c, CHARACTER));
tochar = false;
} else if (c == '\\') {
tochar = true;
} else if (isChar(c)) {
tokens.push_back(Token(c, CHARACTER));
} else if (isBracket(c)) {
tokens.push_back(Token(c, BRACKET));
} else if (isSymbol(c)) {
tokens.push_back(Token(c, SYMBOL));
} else if (isBoundary(c)) {
tokens.push_back(Token(c, BOUNDARY));
} else if (c == '-') {
tokens.push_back(Token(c, HYPHEN));
} else if (c == '|') {
tokens.push_back(Token(c, PIPE));
} else if (c == '.') {
tokens.push_back(Token(c, WILDCARD));
} else {
char message[ERR_SIZE];
snprintf(message, ERR_SIZE, "Invalid token '%c' in \"%s\"", c, pattern);
throw std::runtime_error(message);
}
}
return tokens;
}
};
#endif