string.split(\\s+) 无法处理前导空格
string.split(\\s+) unable to deal with leading spaces
我正在尝试解析此文件以获取每行两个组件:
10000 0
0 10000
3000 7000
7000 3000
20000 21000
3000 4000
14000 15000
6000 7000
我用来扫描和拆分内容的代码是:
BufferedReader br = new BufferedReader(new FileReader(file));
while ((st = br.readLine()) != null){
String[] coordinates = st.split("\s+");
System.out.println("coordinate[0]= " + coordinates[0] + "coordinate[1]= "+ coordinates[1]);
}
我没有得到第二行“0 10000”的预期结果,我得到:
coordinate[0]= coordinate[1]= 0
谁能帮我解决这个问题,让我得到坐标[0]= 0,坐标[1]= 10000。互联网上的所有结果都只谈论 split(\s+) 函数,但我找不到任何解决我面临的问题的东西。
甚至第三行的结果也不正确(开头有一个 space)。
coordinate[0]= coordinate[1]= 3000
一个选项是 trim 整个字符串,然后再拆分它。
String[] coordinates = st.trim().split("\s+");
查看您的输入
你的第一行工作正常,因为行首没有空格。
但是在第 2 行或第 3 行的情况下存在空格。
所以当你打电话给
st.split("\s+");
索引 0 将有空格,索引 1 将具有值,即第二行中的 0
要解决这个问题,您可以 trim 在像这样拆分之前先去掉空白区域
String[] coordinates = st.trim().split("\s+");
您也可以使用 regex 来解决这个问题
(\d+)\s+(\d+)
代码如下:
//read file into a string
String content = new String(Files.readAllBytes(Paths.get(file)), "UTF-8");
//create regex and pattern
Pattern pattern = Pattern.compile("(\d+)\s+(\d+)");
Matcher matcher = pattern.matcher(str);
//output results
while (matcher.find()) {
System.out.print("coordinate[0]= " + matcher.group(1));
System.out.println("coordinate[1]= " + matcher.group(2));
}
我正在尝试解析此文件以获取每行两个组件:
10000 0
0 10000
3000 7000
7000 3000
20000 21000
3000 4000
14000 15000
6000 7000
我用来扫描和拆分内容的代码是:
BufferedReader br = new BufferedReader(new FileReader(file));
while ((st = br.readLine()) != null){
String[] coordinates = st.split("\s+");
System.out.println("coordinate[0]= " + coordinates[0] + "coordinate[1]= "+ coordinates[1]);
}
我没有得到第二行“0 10000”的预期结果,我得到:
coordinate[0]= coordinate[1]= 0
谁能帮我解决这个问题,让我得到坐标[0]= 0,坐标[1]= 10000。互联网上的所有结果都只谈论 split(\s+) 函数,但我找不到任何解决我面临的问题的东西。
甚至第三行的结果也不正确(开头有一个 space)。
coordinate[0]= coordinate[1]= 3000
一个选项是 trim 整个字符串,然后再拆分它。
String[] coordinates = st.trim().split("\s+");
查看您的输入
你的第一行工作正常,因为行首没有空格。
但是在第 2 行或第 3 行的情况下存在空格。
所以当你打电话给
st.split("\s+");
索引 0 将有空格,索引 1 将具有值,即第二行中的 0
要解决这个问题,您可以 trim 在像这样拆分之前先去掉空白区域
String[] coordinates = st.trim().split("\s+");
您也可以使用 regex 来解决这个问题
(\d+)\s+(\d+)
代码如下:
//read file into a string
String content = new String(Files.readAllBytes(Paths.get(file)), "UTF-8");
//create regex and pattern
Pattern pattern = Pattern.compile("(\d+)\s+(\d+)");
Matcher matcher = pattern.matcher(str);
//output results
while (matcher.find()) {
System.out.print("coordinate[0]= " + matcher.group(1));
System.out.println("coordinate[1]= " + matcher.group(2));
}