views:

103

answers:

3

Hello, I am writing a small program to do some calculations.

Basically the input is the following:

-91 10 -4 5

The digits can have the negative sign or not. They are also separated by a space. I need a regular expression to filter each digit including the sign if there is one.

Thanks!

Adam

+3  A: 

in PHP:

$digit=explode(' ', $digitstring);
echo $digit[0]; // return -91

you don't need a regex for this, in PHP.

There are also similar library in other language, such as .Net.

string.split(new char[]{' '});

Here's an example in ruby:

@[email protected](' ')
@my=@m[0];  //-91
Ngu Soon Hui
all his other questions are about ruby... so I'm guessing he wants ruby
jrhicks
you guys are awesome xD. Yes I am indeed writing in Ruby and the split function worked super well!! Thanks!
mr.flow3r
+1  A: 
(-?\d+)\s?

You have to match n times and get the first group from your matcher.

Pseudo code:

matcher = "-91 10 -4 5".match(/(-\d+)\s?/)
while(matcher.hasMatch()) aNumber = match.group(1);

It's easier without regex:

for(x : "-91 10 -4 5".split()) parseInt(x);
Thomas Jung
+1  A: 

You probably want:

(?<=\b)-?\d+(?=\b)

This means:

  • Match (but don't capture) a word boundary (space or beginning of string in this case);
  • Optionally match and capture the hyphen;
  • Match and capture one or more digits; and
  • Match but don't capture a trailing word boundary (being a space or the end of the string in this case).

The non-capturing expressions above are zero-width assertions, technically a positive lookbehind and positive lookahead (respectively).

cletus