[LIB-13] Modify RegexMatcher for searching by type
[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.ChessHogScannerConstants;
23 import org.hedgecode.chess.scanner.regex.AbstractRegexResult;
24 import org.hedgecode.chess.scanner.regex.RegexMatcher;
25 import org.hedgecode.chess.scanner.regex.RegexResult;
26
27 /**
28  * RegexBlockFinder
29  *
30  * @author Dmitry Samoshin aka gotty
31  */
32 public class RegexBlockFinder extends AbstractRegexResult implements RegexMatcher {
33
34     private Pattern startPattern, endPattern;
35     private boolean isMatch;
36     private StringBuilder current;
37     private String key;
38
39     public RegexBlockFinder(String startMatch, String endMatch) {
40         startPattern = Pattern.compile(startMatch);
41         endPattern = Pattern.compile(endMatch);
42         isMatch = false;
43         current = new StringBuilder();
44     }
45
46     @Override
47     public void match(String input) {
48         Matcher matcher = !isMatch ? startPattern.matcher(input) : endPattern.matcher(input);
49         if (matcher.find()) {
50             addCurrent(input);
51             if (isMatch) {
52                 if (key != null) {
53                     add(key, current.toString());
54                 } else {
55                     add(current.toString());
56                 }
57                 current = new StringBuilder();
58             } else {
59                 key = matcher.groupCount() > 0 ? matcher.group(1) : null;
60             }
61             isMatch = !isMatch;
62         } else {
63             if (isMatch) {
64                 addCurrent(input);
65             }
66         }
67     }
68
69     private void addCurrent(String input) {
70         current.append(
71                 input
72         ).append(
73                 ChessHogScannerConstants.CRLF
74         );
75     }
76
77     @Override
78     public RegexResult result() {
79         return this;
80     }
81
82 }