how do I get the value of X, Y, and Z from a string "vt X,Y,Z"
如何得到X,Y,Z的值"vt X,Y,Z"
2 个解决方案
#1
6
As long as the format stays simple like that, I'd use
只要格式保持简单,我就会使用。
String s = "vt X, Y, Z";
String[] values = s.split("[ ,]+");
String x = values[1];
String y = values[2];
String z = values[3];
If the format has more flexibility, you'll want to look into using either a regular expression (the Pattern class) or creating a parser for it using something like ANTLR
如果格式具有更大的灵活性,您将希望使用正则表达式(模式类)或使用类似ANTLR的方法创建解析器。
#2
6
I'd probably opt for a regular expression (assuming X, Y, and Z are ints
):
我可能会选择正则表达式(假设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));
This gives you better handling of invalid input than a simple split on the comma delimiter.
这将使您更好地处理无效输入,而不是简单地在逗号分隔符上进行拆分。
#1
6
As long as the format stays simple like that, I'd use
只要格式保持简单,我就会使用。
String s = "vt X, Y, Z";
String[] values = s.split("[ ,]+");
String x = values[1];
String y = values[2];
String z = values[3];
If the format has more flexibility, you'll want to look into using either a regular expression (the Pattern class) or creating a parser for it using something like ANTLR
如果格式具有更大的灵活性,您将希望使用正则表达式(模式类)或使用类似ANTLR的方法创建解析器。
#2
6
I'd probably opt for a regular expression (assuming X, Y, and Z are ints
):
我可能会选择正则表达式(假设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));
This gives you better handling of invalid input than a simple split on the comma delimiter.
这将使您更好地处理无效输入,而不是简单地在逗号分隔符上进行拆分。