Use regular expressions as terminators
[svjatoslav_commons.git] / src / main / java / eu / svjatoslav / commons / string / tokenizer / Terminator.java
1 /*
2  * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
3  * This project is released under Creative Commons Zero (CC0) license.
4  */
5 package eu.svjatoslav.commons.string.tokenizer;
6
7 import java.util.regex.Matcher;
8 import java.util.regex.Pattern;
9
10 public class Terminator {
11
12     String regexp;
13     public final TerminationStrategy termination;
14     public final String group;
15     public boolean active = true;
16     public final Pattern pattern;
17
18     public Terminator(TerminationStrategy termination, String regexp, String group) {
19         this.termination = termination;
20         this.group = group;
21         this.regexp = regexp;
22         this.pattern = Pattern.compile("^"+regexp);
23     }
24
25     public Matcher match(String source, int index) {
26         Matcher matcher = pattern.matcher(source);
27         matcher.region(index, source.length());
28         return matcher;
29     }
30
31     @Override
32     public String toString() {
33         return "Terminator{" +
34                 "regexp='" + regexp + '\'' +
35                 ", termination=" + termination +
36                 ", group='" + group + '\'' +
37                 ", active=" + active +
38                 '}';
39     }
40
41     public enum TerminationStrategy {
42         /**
43          * Preserve token that is identified within Terminator and return it for processing. For example when
44          * building language parser, it could be used for statements that you want to capture.
45          */
46         PRESERVE,
47
48         /**
49          * While tokens that are marked by Terminator are identified, they are dropped and not returned for consumption.
50          * For example, when building language parser, you might use such strategy for whitespace and comments.
51          * That is, those tokens act as separators between actually useful tokens, but you don't want to consume such
52          * separators or comments in your code.
53          */
54         DROP
55     }
56 }