如何拆分 readLine 但不拆分撇号内的值?

How to split a readLine but dont split values inside apostrophes?

示例 txt 文件

ADD 'Cordless Screwdriver' 30 1 2
COST 'Multi Bit Ratcheting'
FIND 'Thermostat'
FIND 'Hand Truck'
SELL 'Hammer' 1
QUANTITY 'Paint Can'
FIRE 'Joshua Filler'
HIRE 'Lewis hamilton' 35 G
PROMOTE 'Lewis hamilton' M
SCHEDULE

代码

File inputFile = new File("src/edu/iu/c212/resources/input.txt");
        String[] inputWords = null;
        FileReader inputReader = new FileReader(inputFile);
        BufferedReader bri = new BufferedReader(inputReader);
        String y;
        while ((y = bri.readLine()) != null) {
            inputWords = y.split(" ");

--- Project Code That Handles Split Up Lines ---

}

有没有什么办法可以让我在过线时拆分而不拆分撇号内的项目?这样不管第一个项目是一个词还是两个词,如果我调用 inputWords[1] 它总是 return 完整的字符串。

发生了什么:“多位棘轮” -> inputWords[1] -> 'Multi

我想要的:“多位棘轮” -> inputWords[1] -> 'Multi Bit Ratcheting'

您可以使用模式 '.*?'|\S+:

将正则表达式全部查找到每一行
String line = "ADD 'Cordless Screwdriver' 30 1 2";
String[] matches = Pattern.compile("'.*?'|\S+")
                      .matcher(line)
                      .results()
                      .map(MatchResult::group)
                      .toArray(String[]::new);
System.out.println(Arrays.toString(matches));
// [ADD, 'Cordless Screwdriver', 30, 1, 2]

您可以将上述逻辑应用于文件中的每一行。但是,您应该在循环外定义模式,这样就不必为每一行都重新编译它。

您的更新代码:

File inputFile = new File("src/edu/iu/c212/resources/input.txt");
FileReader inputReader = new FileReader(inputFile);
BufferedReader bri = new BufferedReader(inputReader);
Pattern r = Pattern.compile("'.*?'|\S+");
String y;
while ((y = bri.readLine()) != null) {
    List<String> items = new ArrayList<>();
    Matcher m = r.matcher(y);
    while (m.find()) {
        items.add(m.group());
    }

    // use the list here...
}