代码之家  ›  专栏  ›  技术社区  ›  Banks N

如何拆分读线,但不拆分撇号内的值?

  •  1
  • Banks N  · 技术社区  · 2 年前

    示例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],它将始终返回完整的字符串。

    发生了什么:“多位棘轮效应”->输入字[1]->'多个

    我想要的:“多位棘轮效应”->输入字[1]->'多位Ratheting'

    1 回复  |  直到 2 年前
        1
  •  1
  •   Tim Biegeleisen    2 年前

    可以使用该模式将regex find all应用于每一行 '.*?'|\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...
    }