011235813
011235813

Reputation: 35

Regular expression for an integer that's just 0 or any number not starting with 0

I'm using Java for regular expressions in a homework assignment. I'm trying to match integers, but they cannot start with zero (unless it is just zero). I'm having trouble with this code, it compiles but it doesn't correctly match any integer of multiple digits (like 44, 52, 23321, and so forth).

"^[+|-]?[0{1}|([1-9][0-9]*)]$"

EDIT: I found a quick fix, I decided to just create an if statement:

if(string.equals("0")) return "string is an integer";

Upvotes: 0

Views: 1398

Answers (2)

MAcabot
MAcabot

Reputation: 544

The following regex should do the trick:

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

Upvotes: 1

zwol
zwol

Reputation: 140540

You're very close. It looks like you have [] and () confused. Hint: the first bit should be ^[+-]?.

Upvotes: 1

Related Questions