开发者

Regex square bracket help

I need to specify in a regular expression to match all positive and negative numbers. I want it to match only a single - at the start, but if its not present (i.e in a positive number) that should work too.

If I try:

^[-][0-9]+$

This matches only -100, -200, but not 200, 100, etc. How can I cha开发者_运维知识库nge it to match both 100, 200, -100, but not --100?


^-?[0-9]+$

You don't need a character class [] for one character. ? means match zero or one time the previous character/group.


You need the ? modifier (means zero or one). i.e. -? or -{0,1}.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜