检查 ArrayList 中两个双引号之间的元素

Checking element in ArrayList between two double quotes

我正在 Java 中为我制作的自定义语言编写编程语言 reader 的原始版本,我想找出最简单的方法来打印位于 ArrayList 中的元素内容双引号的两个元素之间。这是源代码:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;

public class PrimitiveCompiler {

    public static ArrayList<String> toks = new ArrayList<String>();

    public static void main(String[] args) throws FileNotFoundException {
        String content = readFile("C:\program.txt");

        tokenize(content);
    }

    public static String readFile(String filePath) throws FileNotFoundException {
        File f = new File(filePath);
        Scanner input = new Scanner(f);

        StringBuilder b = new StringBuilder();

        while (input.hasNextLine()) {
            b.append(input.nextLine());
        }

        input.close();

        return b.toString();
    }

    public static ArrayList<String> tokenize(String fContent) {
        int i = 0;
        String tok = "";

        String contents = fContent.replaceAll(" ", "").replaceAll("\n", "").replaceAll("\t", "");

        for(int a = 0; a <= contents.length() - 1; a++) {
            tok += contents.charAt(a);
            i = a;

            if(tokenFinderEquals(tok, "WRITE")) {
                toks.add("WRITE");
                tok = "";
            }
        }

        System.out.println(toks);

        return null;

        }

    public static boolean tokenFinderEquals(String s1, String s2) {
        if(s1.equalsIgnoreCase(s2)) {
            return true;
        }

        return false;
    }
}

现在文本文件的内容只是WRITE,它成功找到它并将其添加到ArrayList。我想做的是计算双引号,当在 ArrayList 中找到两个双引号时,打印出它们之间的每个元素。是可行的还是有另一种更简单的方法来做到这一点?提前致谢!

您需要某种状态来跟踪您是否在引用中。例如:

boolean inQuote = false;
for (int a = 0; a <= contents.length() - 1; a++) {
  char c = contents.charAt(a);
  if (c == '"') {
    // Found a quote character. Are we at the beginning or the end?
    if (!inQuote) {
      // Start of a quoted string.
      inQuote = true;
    } else {
      // End of a quoted string.
      inQuote = false;
      toks.add(tok);
      tok = "";
    }
    // Either way, we don't add the quote char to `tok`.
  } else {
    tok += c;
    if (!inQuote && tokenFinderEquals(tok, "WRITE") {
      // Only look for "WRITE" when outside of a quoted string.
      toks.add(tok);
      tok = "";
    }
  }
}

不过,随着案例的增多,使用像这样的简单循环可能会开始变得困难。您可能想考虑写一个 recursive descent parser.