giulio
giulio

Reputation: 659

Escaping quotes automatically

I have a text file that looks something like:

word("word1");
word("word2");
word("word3");
etc

(copied from a website)

I want to write a java program to get each word (word1, word2 etc) and put it in a String[]. The output would be

my_list = {"word1", "word2" etc};

I wanted put the raw input between brackets to make it a string and then process it, but the problem is I would need to manually escape each of the "" in the file.

How can I workaround this?

Upvotes: 0

Views: 73

Answers (2)

Andie2302
Andie2302

Reputation: 4887

Do you mean something like:

try {
        String text = "word(\"word1\");\n"
                + "word(\"word2\");\n"
                + "word(\"word3\");\n"
                + "etc";
        Pattern pattern = Pattern.compile("\".*?\"");
        Matcher matcher = pattern.matcher(text);
        ArrayList<String> list = new ArrayList<>();
        while (matcher.find()) {
            list.add(matcher.group(0));
        }
        StringBuilder out = new StringBuilder("my_list = {");
        for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
                out.append(iterator.next());
            if(iterator.hasNext())
                out.append(", ");
        }
        out.append("};");
        JOptionPane.showMessageDialog(null, out.toString());
    } catch (PatternSyntaxException ex) {
        // Syntax error in the regular expression
    }

Upvotes: 1

Bitcoin M
Bitcoin M

Reputation: 1206

Why are you even doing word()? If you don't need to, remove it and just have the text file look like this:

word1
word2
word3

If you actually need the text file to look like this, have each line read by being split with:

String thisWord = parsed.split("\"")[1];

Upvotes: 1

Related Questions