我想从具有以下格式的文件中分割数据: {[(1;1;2),(5;1;2),(5;1;1)],[(1;3;2),(5;3;2),(5;1;2 )]}
这是我的 Java 方法:
public void createFromFile(String filename) throws IOException{
BufferedReader br = new BufferedReader(new FileReader(filename));
String s;
while ((s = br.readLine()) != null)
{
s = s.replace("{", "").replace("}", "").replace("]", "").replace(",", "");
ArrayList<Surface> sf = new ArrayList<Surface>();
for(String s1: s.split("\\["))
{ // <== not splitting here
ArrayList<Point> tp = new ArrayList<Point>();
for(String s2: s1.split("\\("))
{ // <== here neither
String[] s3 = s2.split(";");
tp.add(new Point(Double.valueOf(s3[0]),Double.valueOf(s3[1]),Double.valueOf(s3[2])));
}
sf.add(new Surface((Point[]) tp.toArray()));
}
convShape.add(new Body((Surface[])sf.toArray()));
}
}
为什么 s.split("\\[")
和 s.split("\\(")
不拆分 s?
最佳答案
嗯,我认为这应该可行。就您当前的代码而言,它应该正确地拆分它。
但是,鉴于您只想要 numbers
括号内。您不需要split
这里。你让你的工作变得艰难。你最好使用Pattern
和Matcher
类,查找 (
之间的所有内容和)
。您可以使用以下代码寻求帮助:-
String str = "{[(1;1;2),(5;1;2),(5;1;1)],[(1;3;2),(5;3;2),(5;1;2)]}";
Pattern pattern = Pattern.compile("(\\(\\d;\\d;\\d\\),?){3}");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
int i = 1;
System.out.println("Polygon Coordinates: ");
String[] coordinates = matcher.group(0).split(",");
for (String point: coordinates) {
System.out.println("Coordinate " + (i++) + ": " + point);
point = point.replace("\\(", "").replace("\\)", "");
String[] s3 = point.split(";");
tp.add(new Point(Double.valueOf(s3[0]), Double.valueOf(s3[1]),
Double.valueOf(s3[2])));
}
sf.add(new Surface((Point[]) tp.toArray()));
System.out.println();
}
输出:-
Polygon Coordinates:
Coordinate 1: (1;1;2)
Coordinate 2: (5;1;2)
Coordinate 3: (5;1;1)
Polygon Coordinates:
Coordinate 1: (1;3;2)
Coordinate 2: (5;3;2)
Coordinate 3: (5;1;2)
说明:-
(\\(\\d;\\d;\\d\\),?){3}
- 这匹配3 groups
的3 integers
用;
分隔里面brackets
,与groups
由comma(,)
分隔。然后它捕获完整的匹配。matcher.find()
- 从字符串中查找与上述模式匹配的所有内容。matcher.group(0)
- 获得完整的匹配。将整个匹配拆分为
comma(,)
获取单独的坐标如果你想匹配
double
或integer
由;
分隔的值,您需要更改Regex
一点点。我留给你了。参见Pattern class docs有关各种的更多详细信息
quantifiers
。{3}
上述正则表达式中的 是量词之一。
关于java - java split的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13121879/