package Common.Utils; import Common_old.Utils.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); 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) { 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); if (matcher.find()) { String sentence = text_in.substring(matcher.start(), matcher.end()); String prefix_ = getFirstMatch(prefix, sentence); String suffix_ = getFirstMatch(suffix, sentence); String param = sentence.substring(prefix_.length(), sentence.length() - suffix_.length()); return param; } return null; } }