1

i have a string like this one:

288.999,224.004 283.665,258.338 313.332,293.005 312.332,336.671 270.999,389.338 371.998,412.338 

i try to parse the data to float values, but i want to sort it! The value before comma should by my x value and the value after comma should be the y value.

Pattern p = Pattern.compile("[0-9]+.[0-9]*");
Matcher m = p.matcher(pointString);
while(m.find())
{
   System.out.print("x:"+m.group(0)); //x- Values
  // System.out.print("y:"+m.group(1)); //y- Values
}

This code just creates a single group...How should i change my String pattern to get a second group with the y-Values...

favored result:

x:288.999
y:224.004 
x:283.665
y:258.338 
....
1
  • doesn´t work m.group(0) and m.group(1) have the same values! Commented Jun 26, 2013 at 9:38

3 Answers 3

8

Keep it simple, split is enough:

String input = "288.999,224.004 283.665,258.338 313.332,293.005 312.332,336.671 270.999,389.338 371.998,412.338";

String[] points = input.split(" ");
for (String point : points) {
  String[] coordinates = point.split(",");
  System.out.println("x:" + coordinates[0]);
  System.out.println("y:" + coordinates[1]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

got a OutOfBoundsException: length=1 index=1 for System.out.println("y:" + coordinates[1]);
check the contents of coordinates[0], seems like split(","); fails
if there are also \n as a separators, you can use the input.split("\\s");
2

The pattern you are looking for:

((?:\\d*\\.\\d+)|(?:\\d+\\.\\d*)) *, *((?:\\d*\\.\\d+)|(?:\\d+\\.\\d*))

also, group(0) would bring the whole match, you're rather looking for group(1) and group(2)

2 Comments

got a " Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )"
edited, you need to use double "\" when using strings in java
0

This will work

 String str = "288.999,224.004 283.665,258.338 313.332,293.005 312.332,336.671 270.999,389.338 371.998,412.338";
    String[] points=str.split(" ");
    String[] point=new String[2];
    for(int i=0;i<points.length;i++){
        point=points[i].split(",");
        System.out.println("X-val: "+point[0]);
        System.out.println("Y-val: "+point[1]);
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.