拆分后,字符串变为空白

use*_*779 0 java string parsing split

String data = line.split(":")[1];

String location = data.split("|")[0];
String type = data.split("|")[1];

System.out.println("D: " + type);
int x = Integer.parseInt(location.split("-")[0]);
int y = Integer.parseInt(location.split("-")[1]);

int t = Integer.parseInt(type);
Run Code Online (Sandbox Code Playgroud)

输入此解析器的原始字符串格式为"DATA:3,3 | 1".我正在尝试将其解析为"DATA:x,y| t" 的格式.问题是location当字符串从字符串中分离时,该字符串是空白的data.为什么?

sp0*_*00m 8

因为split()正则表达式作为参数,并且|实际上是一个正则表达式特殊字符(并且也是一个语法上有效的正则表达式,这解释了没有抛出错误).

你需要逃避它:或者split("\\|"),或者split("[|]").