Adam Lee
Adam Lee

Reputation: 3003

Need regular expression for this string

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

Upvotes: 0

Views: 199

Answers (3)

Thomas Jung
Thomas Jung

Reputation: 33092

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

Upvotes: 1

cletus
cletus

Reputation: 625287

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

Upvotes: 1

Graviton
Graviton

Reputation: 83284

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

Upvotes: 4

Related Questions