tags:

views:

91

answers:

3

hi, 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

+8  A: 

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
  ^     ^      ^   ^     ^
Gumbo
@Gumbo: Very nice!
kbrimington
Really good! I would have ditched split and ended up with some long regex matcher. Yours is much better.
Nick
thanks a lot :)
pranay
could someone please explain what was wrong with the regex i had tried?
pranay
@pranay - your regex was fine, but splinting is wrong in that case. You may have wanted to `match`, and add capturing groups for both numbers.
Kobi
@Kobi: could you give an example please
pranay
@pranay - Well, not in Java at the moment, but this should make it clearer: http://regexr.com?2rso3 . Note that your regex is correct, I just added groups so I can capture the numbers.
Kobi
@Kobi : thanks.
pranay
+1  A: 

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.

EJP
A: 

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));
}
raja kolluru