[英]What's wrong with my regex to match an integer?
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. 是的,我确定之前已经在StackOverflow上询问过这个问题,但是如果有的话请指点我,因为我找不到它。 There are plenty of regex questions and some are even similar to what I want. 有很多正则表达式的问题,有些甚至与我想要的相似。
Basically, I want to match whole numbers (ie 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. 尝试使用regexper ,在视觉上它看起来就像我想要的那样。 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. 另外,我应该说我正在使用它作为我正在编写的解释器的一部分,因此我想在整数之后允许其他内容。 eg 例如
12 + some_variable
or (more complicatedly)... 或者(更复杂的)......
10.Tostring() <- should still match the '10'
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 .
在1234.5
,子串123
后面没有a .
(because it's followed by a 4
), so it's a valid match. (因为它后跟一个4
),所以这是一个有效的匹配。
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 .
如果您需要允许匹配字符串后面的字符,您可以尝试使用否定前瞻以确保匹配的子字符串后面没有a .
or a digit: 或数字:
^[+-]?\d+(?![\d.])
To also match a string like 10.ToString()
, you could also use a negative lookahead, like this: 为了匹配字符串像10.ToString()
你也可以使用负前瞻,就像这样:
^[+-]?\d+(?!\.?\d)
And another strategy would be to use a positive lookahead, like this: 另一种策略是使用积极的前瞻,如下所示:
^[+-]?\d+(?=\.\D|[^.\d]|$)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.