views:

28

answers:

2

I am trying to extract a number from a string. The number might be zero. Numbers appear like this: '+123', '-8' or '0'.

alert( '+123'.match(/[-?|+?]\d+/) );
alerts +123

alert( '-8'.match(/[-?|+?]\d+/) );
alerts -8

alert( '0'.match(/[-?|+?]\d+/) );
alerts null // why oh why?

How do I get '0'.match(/[-?|+?]\d+/) to return 0 instead of null?

+6  A: 

The pattern

[-?|+?]

will match exactly one -, +, | or a ?. What you want is

[-+]?

which will match a - or a + one or zero times.

This will allow numbers like '123' to pass as well. If you require the + sign, use this:

/0|[-+][1-9]\d*/
KennyTM
Which is not what he wants. A number has only one prefix (if any)
Sean Kinsey
@Sean: I don't understand. Any counterexample?
KennyTM
My bad, I misread :) But that last regexp looks like overkill, unless its important to disallow -0/+0
Sean Kinsey
@Sean: I think you misread the answer. The final regex provided is an alternative if the `+` or `-` is required when the number is not `0`. It will allow only one prefix.
Andy E
@Andy, indeed I did - still haven't got my first cup of coffee :)
Sean Kinsey
@Sean: tell me about it, can't get good help these days ;-) */end of hijack*
Andy E
A: 

Here

var rePattern = /[+-]?\d+/;

"0".match(rePattern) // 0
"+44".match(rePattern) //+44
"-3".match(rePattern) //-3

Note this is not as strict as Kenny's

Sean Kinsey