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]
Naman
  • 27,789
  • 26
  • 218
  • 353
  • Is the input in HTML, which you would first need to parse? – Sweeper Aug 04 '19 at 03: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. – user11620797 Aug 04 '19 at 04: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? – Sweeper Aug 04 '19 at 04:34
  • @Sweepr, Thanks for your patience. What I meant is the input is a String. – user11620797 Aug 04 '19 at 04: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? – Sweeper Aug 04 '19 at 04:42
  • @Sweeper, we have tried using some parser, but was not successful. For time-being we are trying an alternate solution. Thanks a lot for your advice. – user11620797 Aug 04 '19 at 05:04

1 Answers1

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());
Ranjeet
  • 116
  • 6