Reputation: 2369
i have expressions like :
-3-5
or -3--5
or 3-5
or 3-+5
or -3-+5
I need to extact the numbers , splitting on the "-" sign between them i.e in the above cases i would need, -3 and 5, -3 and -5 , 3 and 5, 3 and +5 , -3 and +5. I have tried using this:
String s[] = str.split("[+-]?\\d+\\-[+-]?\\d+");
int len = s.length;
for(int i=0;i<len;i++)System.out.println(s[i]);
but it's not working
Upvotes: 1
Views: 116
Reputation: 602
Your expression is pretty ok. Split is not the choice though since you are trying to match the expression to your string - not split the string using it:
Here is some code that can make use of your expression to obtain what you want:
String a = "-90--80";
Pattern x = Pattern.compile("([+-]?\\d+)\\-([+-]?\\d+)");
Matcher m = x.matcher(a);
if(m.find()){
System.out.println(m.group(1));
System.out.println(m.group(2));
}
Upvotes: 0
Reputation: 310909
Crossposted to forums.sun.com.
This is not a job for REs by themselves. You need a scanner to return operators and numbers, and an expression parser. Consider -3-------5.
Upvotes: 1
Reputation: 655269
Try to split with this regular expression:
str.split("\\b-")
The word boundary \b
should only match before or after a digit so that in combination with -
only the following -
as the range indicator is matched:
-3-5, -3--5 , 3-5,3-+5,-3-+5
^ ^ ^ ^ ^
Upvotes: 8