2e50b8cdc5bda91b71beb67a77063b34e9afd442
[chesshog-scanner.git] / src / main / java / org / hedgecode / chess / scanner / regex / type / RegexBlockFinder.java
1 /*
2  * Copyright (c) 2019-2020. Developed by Hedgecode.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.hedgecode.chess.scanner.regex.type;
18
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
21
22 import org.hedgecode.chess.scanner.regex.AbstractRegexResult;
23 import org.hedgecode.chess.scanner.regex.RegexMatcher;
24 import org.hedgecode.chess.scanner.regex.RegexResult;
25
26 import static org.hedgecode.chess.scanner.ChessHogScannerConstants.*;
27
28 /**
29  * RegexBlockFinder
30  *
31  * @author Dmitry Samoshin aka gotty
32  */
33 public class RegexBlockFinder extends AbstractRegexResult implements RegexMatcher {
34
35     private Pattern startPattern, endPattern;
36     private boolean isMatch;
37     private StringBuilder current;
38     private String key;
39
40     public RegexBlockFinder(String startMatch, String endMatch) {
41         startPattern = Pattern.compile(startMatch);
42         endPattern = Pattern.compile(endMatch);
43         isMatch = false;
44         current = new StringBuilder();
45     }
46
47     @Override
48     public void match(String input) {
49         Matcher matcher = !isMatch ? startPattern.matcher(input) : endPattern.matcher(input);
50         if (matcher.find()) {
51             addCurrent(input);
52             if (isMatch) {
53                 if (key != null) {
54                     add(key, current.toString());
55                 } else {
56                     add(current.toString());
57                 }
58                 current = new StringBuilder();
59             } else {
60                 key = matcher.groupCount() > 0 ? matcher.group(1) : null;
61             }
62             isMatch = !isMatch;
63         } else {
64             if (isMatch) {
65                 addCurrent(input);
66             }
67         }
68     }
69
70     private void addCurrent(String input) {
71         current.append(
72                 input
73         ).append(
74                 CRLF
75         );
76     }
77
78     @Override
79     public RegexResult result() {
80         return this;
81     }
82
83 }