-4

I'm reading a response from a source which is an journal or an essay and I have the html response as a string like:

According to some, dreams express "profound aspects of personality" (Foulkes 184), though "others disagree" but truth is.

My goal is just to extract all of the quotes out of the given string and save each of them into a list. And add space in original string in place of quotes.

Scarlet
  • 15
  • 1
  • 6
  • Use a regexp pattern such as `"\".*?\""` and then use `Pattern#matches` followed by `Matcher#find`. Happy programming. – Maarten Bodewes Dec 07 '19 at 13:02
  • so do you want to put all quotes to the ArrayList and then replace all quotes of the string by space? correct me if I'm wrong. – Mak-Mak Basaya Dec 07 '19 at 13:08
  • Note that above trick with `find` will also allow you to get the begin and end index of each match, so the second step of changing the string should be easy. I don't really want to give a full answer, this is not a code service after all. – Maarten Bodewes Dec 07 '19 at 13:14

1 Answers1

1

This code will replace all quotes with one space and save quotes without brackets in the list:

public static void main(String[] args) {    
        String str = "According to some, dreams express \"profound aspects of personality\" (Foulkes 184), though \"others disagree\" but truth is.";
        Pattern pattern = Pattern.compile("\".*?\"");
        Matcher matcher = pattern.matcher(str);

        List<String> quotes = new ArrayList<>();
        StringBuffer buffer = new StringBuffer();

        while (matcher.find()) {
            String quote = matcher.group();
            int length = quote.length();
            quotes.add(quote.substring(1, length - 1));
            matcher.appendReplacement(buffer, " ");
        }
        matcher.appendTail(buffer);

        System.out.println(buffer.toString());
        System.out.println(quotes);
    }

This solution needs some additional fixes depends on existence of empty brackets in a text, but it work in your case.

Output:

According to some, dreams express (Foulkes 184), though but truth is.

[profound aspects of personality, others disagree]

Community
  • 1
  • 1
Egor
  • 1,334
  • 8
  • 22
  • 1
    @Maarten-reinstateMonica yes, StringBuilder is more efficient, but appendReplacement method works only with StringBuffer – Egor Dec 09 '19 at 08:25
  • Right, interesting! I can understand that they removed it, it is a bit surprising kind of functionality and it requires additional state it seems. But I always thought of `StringBuilder` as a more efficient, non-thread safe version of `StringBuffer`... I never imagined they left out functionality. I'll remove my comments above and this comment as they start to be off topic... – Maarten Bodewes Dec 09 '19 at 15:44