What is wrong with my regex to match an integer?

Yes, I'm sure this was set earlier in StackOverflow, but if so, please point me to it because I could not find it. There are many regular expression questions, and some even look like what I want.

Basically, I want to match integers (i.e. integers), both positive and negative. So nothing that ends with a decimal point and then more digits. I am only interested in the numbering of the English language, I do not want to allow thousands of separators, etc., And I want to use only ".". as a decimal point, none of these weird โ€œcommasโ€ are the decimal points that some countries make.

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

But the above is as follows ...

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

Try it on regexper , visually it looks exactly the way I want. I am new to negative views, so I obviously missed something, but what is it?

In addition, I must say that I use this as part of the interpreter that I am writing, and therefore I want to allow additional content after the integer. eg.

12 + some_variable

or (more complicated) ...

10.Tostring()  <- should still match the '10'
+3
source share
1 answer

Your pattern matches any sequence of digits not accompanied by a character .and another digit. The 1234.5substring 123does not follow a .(because it follows 4), so this is a valid match.

($), , :

^[+-]?\d+$

, , lookahead, , . :

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


10.ToString(), , :

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

, :

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

+4

All Articles