简体   繁体   中英

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?

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];

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM