Farhad-Taran
Farhad-Taran

Reputation: 6512

regex to allow "single 0" or " any other number of digits?

I need a regex to allow either a single 0 or any other number of digits that do not start with zero so:

0 or 23443 or 984756 are allowed but 0123 is not allowed.

I have got the following which allows only 1 to 9

[1-9]\d

Upvotes: 4

Views: 3345

Answers (2)

Andy Lester
Andy Lester

Reputation: 93676

You don't need to force everything into a single regex to do this.

It will be far clearer if you use multiple regexes, each one making a specific check. In Perl, you would do it like this, but you can adapt it to C# just fine.

if ( ($s eq '0') || (($s =~ /^\d+$/) && not ($s =~ /^0/)) )

You have made explicitly clear what the intent is:

if ( (string is '0') OR ((string is all digits) AND (string does not start with '0')) )

Note that the first check to see if the string is 0 doesn't even use a regex at all, because you are comparing to a single value.

Let the expressive form of your host language be used, rather than trying to cram logic into a regex.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361625

Look for a lone 0 or 1-9 followed by any other digits.

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

If you want to match numbers inside of larger strings, use the word boundary marker \b in place of ^ and $:

\b(0|[1-9]\d*)\b

Upvotes: 7

Related Questions