Hossein Mobasher
Hossein Mobasher

Reputation: 4472

Regular Expression to split (...,...)

I am new in Regular Expression. How can i split Points data from the line below :

((X1,Y1),(X2,Y2),(X3,Y3))

Spliting to :

(X1,Y1)
(X2,Y2)
(X3,Y3)

Thanks in Advance :)

Upvotes: 0

Views: 101

Answers (2)

assylias
assylias

Reputation: 328618

Here is an alternative to the other answer, which looks for (XXX,YYY) types of patterns:

String s = "((X1,Y1),(X2,Y2),(X3,Y3))";
Matcher m = Pattern.compile("(\\(\\w+,\\w+\\))").matcher(s);
while(m.find()) {
    System.out.println(m.group());
}

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213263

Well, extracting contents out of brackets or parenthesis may very soon become complex with regex, when nested brackets are introduced. But still in your current case, it seems you can get your results with the use of Pattern and Matcher class (Don't try to split, as it would be slightly more complex):

String str = "((X1,Y1),(X2,Y2),(X3,Y3))";

// The below pattern will fail with nested brackets - (X1, (X2, Y2)). 
// But again, that doesn't seem to be the case here.    
Matcher matcher = Pattern.compile("[(][^()]*[)]").matcher(str);

while (matcher.find()) {
    System.out.println(matcher.group());
}

Upvotes: 2

Related Questions