MikroDel
MikroDel

Reputation: 6735

Regex. Up to six digits after separator but not all zeros

I need input in this form:

first digit ist always 0
second is always . or ,
than up to six digits, but only digits not letters or other symbols and not all zeros

private const string Pattern = @"^0(,|.)(?!0+$)+";

var regex = new Regex(Pattern, RegexOptions.IgnoreCase);

if (!regex.IsMatch(inputToCheck))
{...}

This works ok for all the conditions except one with digits only. This input should be disabled too: "0,01a", "0.01a1", "0,01a0"

How can I extend my regex pattern to this condition?

Some examples of valid and invalid input.

Valid:
0,123456
0,01
0,010
0,2

invalid:
1,123456
2,123456
0,0
0,00
0,000
a
a,1
0,01a
0,01a1
0,01a0

Upvotes: 0

Views: 562

Answers (4)

mroemore
mroemore

Reputation: 131

I think you're on the right track. Here's my solution to this:

^0[,.](?!0+$)\d{1,6}$

This will make sure that the first digit is zero. It then checks that the next character is either a comma or a dot. Then, using a lookahead it ensures that the rest of the subject string is not entirely zeros. If this passes, it checks that the remaining characters are all digits.

Upvotes: 4

Sayse
Sayse

Reputation: 43300

You shouldn't really be using regex to parse numbers, you can do it by just validating it as a number as so..

    CultureInfo culture = new CultureInfo("de-DE");
    string[] inputs = new string[]{"0,123456",
                                    "0,01",
                                    "1,123456",
                                    "0,0"};
    foreach(var input in inputs)
    {
    double val;
    if(Double.TryParse(input, NumberStyles.Number, culture, out val) 
        && Math.Round(val, 6) == val
        && val != 0.0
        && (int)val == 0)
        Console.WriteLine("{0} is valid", input);
    else
        Console.WriteLine("{0} is invalid", input);
    }

Output

0,123456 is valid

0,01 is valid

1,123456 is invalid

0,0 is invalid

IDEOne example

Upvotes: 1

Med.Amine.Touil
Med.Amine.Touil

Reputation: 1235

Try this expression

^^0(,|.)([0-9]{1,4}$)+

Upvotes: 1

Federico Piazza
Federico Piazza

Reputation: 30995

You can use a regex like this:

^0[.,][1-9]{0,6}$

Regular expression visualization

Of course this regex don't allow 0 after the , or .. If you want to allow 0 but restrict ending by 0 you can do:

^0[.,][0-9]{0,5}[1-9]$

And also you can shorten it a little to:

^0[.,]\d{0,5}[1-9]$

Upvotes: 2

Related Questions