开发者

Regex square bracket help

开发者 https://www.devze.com 2023-03-25 06:42 出处:网络
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 wor

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

精彩评论

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

关注公众号