package Common.Utils; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringTemplate { //https://javarush.ru/groups/posts/regulyarnye-vyrazheniya-v-java public static String separator = "(\\s)+"; //хотя бы один пробел public static String parameter = "(.)+"; //хотя бы один символ //------------------------------------------------------------------ public String prefix = ""; //часть команды до параметра, запакованная через пробел public String suffix = ""; //часть команды после параметра, запакованная через пробел public String pattern = ""; //------------------------------------------------------------------ public StringTemplate(String p, String s) { prefix = Utils.pack(p); suffix = Utils.pack(s); // System.out.println(Utils.Brackets(prefix)); // System.out.println(Utils.Brackets(suffix)); String[] prefix_words = prefix.split(" "); String[] suffix_words = suffix.split(" "); //настраиваем регулярное выражение---------- prefix = "^(\\s)*"; for (String word : prefix_words) { if (!word.isEmpty()) prefix += (word + separator); } suffix = ""; for (String word : suffix_words) { if (!word.isEmpty()) suffix += (separator + word); } suffix += "(\\s)*$"; pattern = prefix + parameter + suffix; } public static String getFirstMatch(String pattern_in, String text_in) { Matcher m = Pattern.compile(pattern_in, Pattern.CASE_INSENSITIVE).matcher(text_in); m.find(); return text_in.substring(m.start(), m.end()); } public boolean check(String text_in) { // System.out.println("sentense = " + Utils.Brackets(text_in)); // System.out.println("pattern = " + Utils.Brackets(pattern)); return Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE).matcher(text_in).find(); } public String check_and_get_param(String text_in) { Pattern regex = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); Matcher matcher = regex.matcher(text_in); // System.out.println("sentense = " + Utils.Brackets(text_in)); // System.out.println("pattern = " + Utils.Brackets(pattern)); if (matcher.find()) { // System.out.println("match found " + matcher.start() + " " + matcher.end()); String sentence = text_in.substring(matcher.start(), matcher.end()); // System.out.println("sentence=" + Utils.Brackets(sentence)); String prefix_ = getFirstMatch(prefix, sentence); // System.out.println("prefix_ = " + Utils.Brackets(prefix_)); String suffix_ = getFirstMatch(suffix, sentence); // System.out.println("suffix_ = " + Utils.Brackets(suffix_)); String param = sentence.substring(prefix_.length(), sentence.length() - suffix_.length()); // System.out.println("param = " + Utils.Brackets(param)); return param; } return null; } }