TemplateParser { static List<TextFragment> parseTemplateString(String template) { ArrayList<TextFragment> fragments = new ArrayList<>(); Matcher fragmentMatcher = DYNAMIC_FRAGMENT_PATTERN.matcher(template); int position = 0; while (position < template.length()) { if (!fragmentMatcher.find(position)) { String prefix = template.substring(position); fragments.add(staticFragment(prefix)); break; } final int prefixStart = position; final int prefixEnd = fragmentMatcher.start(1) - "{{".length(); final int dynamicStart = fragmentMatcher.start(1); final int dynamicEnd = fragmentMatcher.end(1); if (prefixEnd - prefixStart > 0) { String prefixText = template.substring(prefixStart, prefixEnd); fragments.add(staticFragment(prefixText)); } String dynamicFragmentText = template.substring(dynamicStart, dynamicEnd); fragments.add(dynamicFragment(dynamicFragmentText)); position = dynamicEnd + "}}".length(); } return fragments; } private  TemplateParser();   }
@Test public void exampleUsage() { List<TextFragment> fragments = TemplateParser.parseTemplateString("hello-{{world}}"); assertThat( fragments, contains(staticFragment("hello-"), TextFragment.dynamicFragment("world"))); }
@Test public void anotherExample() { List<TextFragment> fragments = TemplateParser.parseTemplateString("io.example/greet-python/{{$.who[0].what[5].name}}"); assertThat( fragments, contains( staticFragment("io.example/greet-python/"), TextFragment.dynamicFragment("$.who[0].what[5].name"))); }
@Test public void longDynamicText() { List<TextFragment> fragments = TemplateParser.parseTemplateString("{{this text should be dynamic}}"); assertThat(fragments, contains(TextFragment.dynamicFragment("this text should be dynamic"))); }
@Test public void twoDynamicFragmentsWithSeparator() { List<TextFragment> fragments = TemplateParser.parseTemplateString("{{hello}}/{{world}}"); assertThat( fragments, contains( TextFragment.dynamicFragment("hello"), staticFragment("/"), TextFragment.dynamicFragment("world"))); }
@Test public void twoDynamicFragmentsWithoutSeparator() { List<TextFragment> fragments = TemplateParser.parseTemplateString("{{hello}}{{world}}"); assertThat( fragments, contains(TextFragment.dynamicFragment("hello"), TextFragment.dynamicFragment("world"))); }
@Test public void noDynamicText() { List<TextFragment> fragments = TemplateParser.parseTemplateString("hello world"); assertThat(fragments, contains(staticFragment("hello world"))); }
@Test public void dynamicFragmentToTheLeft() { List<TextFragment> fragments = TemplateParser.parseTemplateString("{{hello}}-world"); assertThat( fragments, contains(TextFragment.dynamicFragment("hello"), staticFragment("-world"))); }
@Test public void unclosedInterpolatedTextConsideredASticFragment() { assertThat(TemplateParser.parseTemplateString("{{"), contains(staticFragment("{{"))); }