2009-04-10 100 views

回答

6

只要格式保持简单的样子,我会使用

String s = "vt X, Y, Z"; 
String[] values = s.split("[ ,]+"); 
String x = values[1]; 
String y = values[2]; 
String z = values[3]; 

如果格式有更多的灵活性,你要考虑使用一个正则表达式(在Pattern类),或创建一个使用类似ANTLR

+0

它可以与Z一起工作吗? Z之后没有。 – William 2009-04-10 21:24:37

6

我可能会选择一个正则表达式它解析器(假设X,Y和Z是ints):

Pattern p = Pattern.compile("vt ([0-9]+),\\s*([0-9]+),\\s*([0-9]+)"); 
Matcher m = p.match(line); 
if (!m.matches()) 
    throw new IllegalArgumentException("Invalid input: " + line); 
int x = Integer.parseInt(m.group(1)); 
int y = Integer.parseInt(m.group(2)); 
int z = Integer.parseInt(m.group(3)); 

与逗号分隔符上的简单拆分相比,可以更好地处理无效输入。

相关问题