2014-04-01 55 views
0
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); 

输入到此解析器中的原始字符串的格式类似于“DATA:3,3 | 1”。我试图将其解析为“DATA:xy | t”的格式。问题是字符串location与字符串data分离时为空。为什么?字符串在分割时变成空白

回答

8

因为split()需要一个正则表达式作为参数,而|实际上是一个正则表达式特殊字符(也是一个语法上有效的正则表达式,它解释了没有错误被抛出)。

您需要转义它:split("\\|")split("[|]")

0

正如sp00m说,你可以使用:

split("\\|")split("[|]")

或者你可以使用

split(Pattern.quote("|")); 

预先测试,如果字符串中包含的字符,只是使用

字符串#包括()

if (string.contains("\\|")) { 
    // Split it. 
} 
else { 
    throw new IllegalArgumentException("String " + string + " does not contain |"); 
}