-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegExTokenFactory.java
More file actions
56 lines (45 loc) · 1.36 KB
/
RegExTokenFactory.java
File metadata and controls
56 lines (45 loc) · 1.36 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
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A TokenFactory that uses regular expressions
* to specify the kinds of tokens it produces.
*/
public class RegExTokenFactory extends TokenFactory {
private final Matcher matcher;
/**
* Create a factory that produces tokens that match the given regular expression.
* @param regEx The regular expression to use for identifying tokens
*/
public RegExTokenFactory(final String regEx) {
super();
final Pattern pattern = Pattern.compile(regEx);
matcher = pattern.matcher("");
}
@Override
public void setText(final String text) {
matcher.reset(text);
}
@Override
public boolean find(final int startFrom) {
final boolean found = matcher.find(startFrom);
return found && startFrom == matcher.start();
}
@Override
public int getTokenLength() {
return matcher.end() - matcher.start();
}
/**
* Get the position at which we last tried to find a token.
* @return The start position of the last call to find(...)
*/
protected int getTokenStartPosition() {
return matcher.start();
}
/**
* The text of the token.
* @return The text of the token we found.
*/
protected String getTokenText() {
return matcher.group();
}
}