zrabzdn
zrabzdn

Reputation: 1435

Regex c# only positive numbers

I am looking for a regular expression that validates only positive numbers(integers):

0-999 and first number not 0.

My example not work:

string pattern = @"^\d+$";

How decided positive numbers pattern?

Upvotes: 2

Views: 22168

Answers (6)

dariamap
dariamap

Reputation: 1

The positive number with two digits after comma:

\d*\,\d\d

Upvotes: -1

nicolas
nicolas

Reputation: 7668

If you just want to validate an input, why not using TryParse?

Regular Expression for positive numbers in C#

        double result = 0;
        if (Double.TryParse(myString, out result))
        {
            // Your conditions
            if (result > 0 && result < 1000)
            {
                // Your number
            }
        }

Upvotes: 2

michele
michele

Reputation: 2091

You can use a lot of useful regex tools online like http://gskinner.com/RegExr/

there's a lot of ready to use examples from which you can start to get your own!

Upvotes: 0

burning_LEGION
burning_LEGION

Reputation: 13450

use this regular expression ^[1-9]\d{0,2}$

Upvotes: 2

melwil
melwil

Reputation: 2553

You could force the first digit to be 1-9, and then have any or no digits follow it, like so;

string pattern = @"^[1-9]\d*$";

You can also restrict the amount of digits by putting a numbered constraint on it.

string pattern = @"^[1-9]\d{0,2}$";

The top one will accept any positive integer >0, while the bottom one will accept only 1-999.

Upvotes: 17

Bob Vale
Bob Vale

Reputation: 18474

How about

@"^[1-9]\d?\d?$"

1-9 followed by 2 optional digits?

Upvotes: 5

Related Questions