如何分割一个readLine,但不分割值内撇号?



文本文件示例

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 ---
}

是否有一种方法,我可以有拆分不拆分项目在撇号内,当越过线?这样,无论第一个Item是一个单词还是两个单词,如果我调用inputWords[1],它将始终返回完整的字符串。

发生了什么:"多比特棘轮";→inputWords[1]→"多

我想要的:"多比特棘轮";→inputWords[1]→"多比特棘轮">

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

对每行应用正则表达式find all
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...
}

最新更新