[LIB-9] Set of entities for PGN parsing and formatting
[chesshog.git] / chesshog-format / src / main / java / org / hedgecode / chess / pgn / PGNUtils.java
1 /*
2  * Copyright (c) 2018-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.pgn;
18
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
21
22 /**
23  * PGNUtils
24  *
25  * @author Dmitry Samoshin aka gotty
26  */
27 public final class PGNUtils {
28
29     private static final char BACKSLASH = '\\';
30     private static final String SHIELD_REGEX = "\\\\";
31
32     private static final String CRLF = "\\r?\\n";
33     private static final String SPACE = " ";
34
35     public static String match(String source, String regex) {
36         Matcher matcher = Pattern.compile(
37                 regex,
38                 Pattern.MULTILINE
39         ).matcher(source);
40         if (matcher.find()) {
41             return matcher.groupCount() > 0
42                     ? matcher.group(1)
43                     : matcher.group();
44         }
45         return null;
46     }
47
48     public static boolean isPgn(String source) {
49         return match(
50                 source,
51                 PGNConstants.PGN_DETECT_REGEX
52         ) != null;
53     }
54
55     public static String shield(String source, char[] shields) {
56         for (char shield : shields) {
57             if (source.indexOf(shield) >= 0) {
58                 String regexShield =
59                         shield == BACKSLASH
60                                 ? SHIELD_REGEX
61                                 : String.valueOf(shield);
62                 source = source.replaceAll(
63                         String.format("([%s])", regexShield),
64                         SHIELD_REGEX.concat("$1")
65                 );
66             }
67         }
68         return source;
69     }
70
71     public static String stripCrlf(String pgn) {
72         return pgn.replaceAll(CRLF, SPACE);
73     }
74
75     private PGNUtils() {
76         throw new AssertionError(
77                 String.format("No %s instances!", getClass().getName())
78         );
79     }
80
81 }