0

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

1
  • Take a look at txt2re.com it ought to help with a lot of this sort of problem. Commented Oct 3, 2009 at 18:23

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

all his other questions are about ruby... so I'm guessing he wants ruby
you guys are awesome xD. Yes I am indeed writing in Ruby and the split function worked super well!! Thanks!
1

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).

Comments

1
(-?\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);

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.