0
|
1 package nabble.naml.namespaces;
|
|
2
|
|
3 import nabble.naml.compiler.Command;
|
|
4 import nabble.naml.compiler.CommandSpec;
|
|
5 import nabble.naml.compiler.IPrintWriter;
|
|
6 import nabble.naml.compiler.Interpreter;
|
|
7 import nabble.naml.compiler.Namespace;
|
|
8
|
|
9 import java.util.regex.Matcher;
|
|
10
|
|
11
|
|
12 @Namespace (
|
|
13 name = "regex",
|
|
14 global = true
|
|
15 )
|
|
16 public class RegexNamespace extends Sequence {
|
|
17 private final Matcher matcher;
|
|
18 private final String source; // only for debugging
|
|
19 private boolean started = false;
|
|
20 private boolean isFound = false;
|
|
21
|
|
22 public RegexNamespace(Matcher matcher,String source) {
|
|
23 this.matcher = matcher;
|
|
24 this.source = source;
|
|
25 }
|
|
26
|
|
27 private boolean find() {
|
|
28 started = true;
|
|
29 return isFound = matcher.find();
|
|
30 }
|
|
31
|
|
32 @Command public void find(IPrintWriter out,Interpreter interp) {
|
|
33 out.print( find() );
|
|
34 }
|
|
35
|
|
36 @Command public void matches(IPrintWriter out,Interpreter interp) {
|
|
37 out.print( matcher.matches() );
|
|
38 }
|
|
39
|
|
40 public static final CommandSpec found = new CommandSpec.Builder()
|
|
41 .optionalParameters("group")
|
|
42 .build()
|
|
43 ;
|
|
44
|
|
45 @Command public void found(IPrintWriter out,Interpreter interp) {
|
|
46 String group = interp.getArgString("group");
|
|
47 out.print( group==null ? matcher.group() : matcher.group(Integer.parseInt(group)) );
|
|
48 }
|
|
49
|
|
50 @Command public void has_more_elements(IPrintWriter out,Interpreter interp) {
|
|
51 if( !started ) {
|
|
52 out.print( matcher.find() );
|
|
53 matcher.reset();
|
|
54 } else if( isFound ) {
|
|
55 int start = matcher.start();
|
|
56 out.print( matcher.find() );
|
|
57 if( !matcher.find(start) )
|
|
58 throw new RuntimeException();
|
|
59 } else {
|
|
60 out.print( false );
|
|
61 }
|
|
62 }
|
|
63
|
|
64 @Command public void next_element(IPrintWriter out,Interpreter interp) {
|
|
65 out.print( find() );
|
|
66 }
|
|
67
|
|
68 @Command public void current_element(IPrintWriter out,Interpreter interp) {
|
|
69 out.print( matcher.group() );
|
|
70 }
|
|
71
|
|
72 }
|