1

I have a string with a number of place holders, is there any way if we can collect all the place holders in one go with the help of java streams?

Input:

<Html>
 <Table>
  <TR><TD>||BuySell||</TD></TR>
  <TR><TD>||ExchangeName||</TD></TR>
 </Table>
</Html>      

Output:

List<String> placeholders = [BuySell,ExchangeName]
6
  • Is the input in HTML, which you would first need to parse? Commented Aug 4, 2019 at 3:56
  • @Sweeper, Thanks for your reply. No it is a string. I have broken down the fixed html templates to different sub templates of Strings. Commented Aug 4, 2019 at 4:28
  • Have you? The input you showed here seems to me like a HTML string though, not a "different sub templates of Strings", whatever that means. Can you clarify? Commented Aug 4, 2019 at 4:34
  • @Sweepr, Thanks for your patience. What I meant is the input is a String. Commented Aug 4, 2019 at 4:40
  • Yes, I know the input is a String now, but is it HTML? If so, you should use an HTML parser. Are you using an HTML parser? Commented Aug 4, 2019 at 4:42

1 Answer 1

0

This can be done using a helper function.

    BiFunction<Matcher, Function<Matcher, Object>, Collection<?>> placeHolderExtractor = (mch, extracter) -> {
        List<Object> list = new ArrayList<>();
        while(mch.find()) {
            list.add(extracter.apply(mch));
        }

        return list;
    };

    String htmlStr = "<Html> <Table>  <TR><TD>||BuySell||</TD></TR>  <TR><TD>||ExchangeName||</TD></TR> </Table></Html>";
    String regex = "(\\|\\|)([\\w]+)\\1";

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher =  pattern.matcher(htmlStr);

    List<String> placeHolderList = placeHolderExtractor.apply(matcher, macher -> macher.group(2))
    .stream()
    .map(String::valueOf)
    .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.