ejbs
ejbs

Reputation: 390

Matching numbers with regex

I need to match numbers where the first character is either a - (minus) or NOT a 0 (unless it's the only character in the string) and I'm kinda stuck. ^[-|1-9]?[0-9]+ I've currently got this but it'll match any amount of zeroes.

Examples:

Should match:

-16
25
2005

Should not match:

-05
05
00001
0-017

Upvotes: 0

Views: 65

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 148980

Try a pattern like this:

^-?[1-9][0-9]*$

This will match optional - at the start of the string, followed by a single digit from 1 to 9, followed by zero or more digits from 0 to 9. The start (^) and end ($) anchors ensure that no other characters are allowed before or after the number.

Demonstration

Update It has been pointed out that the above pattern will match any positive or negative decimal integer without leading zeros, but it will not match zero, itself. To handle that case, add an alternation to your pattern like this:

^-?[1-9][0-9]*$|^0$

Or like this:

^(-?[1-9][0-9]*|0)$

Upvotes: 3

Related Questions