Question

Yes, I'm sure this has been asked before on StackOverflow, but if so please point me to it, because I couldn't find it. There are plenty of regex questions and some are even similar to what I want.

Basically, I want to match whole numbers (i.e. integers), both positive and negative. So nothing that ends with a decimal point followed by more digits. I only care about the English style numbering, I don't want to allow thousand separators, etc., and I only want to use a '.' as a decimal point, none of this strange 'comma is a decimal point' that some countries do.

^[+-]?\d+(?!\.\d)

But the above seems to match as follows...

10      matches '10'       <- yay
465654  matches '465654'   <- yay
653.56  only matches '65'  <- boo
1234.5  only matches '123' <- also boo!

Trying this out on regexper, visually it looks exactly like what I want. I'm new to negative lookaheads, so I've obviously missed something here, but what is it?

Also, I should say I'm using this as part of an interpreter I'm writing, and therefore I want to allow additional content after the integer. e.g.

12 + some_variable

or (more complicatedly)...

10.Tostring()  <- should still match the '10'
Était-ce utile?

La solution

Your pattern matches any sequence of digits not followed by a . and another digit. In 1234.5 the substring 123 is not followed by a . (because it's followed by a 4), so it's a valid match.

Try using an end anchor ($) to ensure that no additional characters appear after the matched string:

^[+-]?\d+$

If you need to allow characters following the matched string, you might try using a negative lookahead to ensure that the matched substring is not followed by a . or a digit:

^[+-]?\d+(?![\d.])

Demonstration


To also match a string like 10.ToString(), you could also use a negative lookahead, like this:

^[+-]?\d+(?!\.?\d)

Demonstration

And another strategy would be to use a positive lookahead, like this:

^[+-]?\d+(?=\.\D|[^.\d]|$)

Demonstration

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top