0
votes

I am looking for a regex to accept only numbers and comma but not 0,decimal,special characters,negative numbers and white-space between the numbers.It can allow White-space at the start and end of the value.Also It should allow 0 for 10,100,20 but I don't want the textbox to allow a single digit zero.

I have tried multiple options but I couldn't find one that solve my problem.

string testAnswer = textbox.value;
Regex answerRegex = new Regex(@"\s+(?<!-)[1-9][0-9,]*\s+");
if (testAnswer.Contains(","))
{
    testAnswer = testAnswer.Replace(",", "");
    Response.Write(testAnswer);
}
Match answerMatch = answerRegex.Match(testAnswer.Trim());
if (testAnswer == String.Empty || !answerMatch.Success)
{
    valid = false;
    answer.CssClass = "error";
}           
else
{
    answer.CssClass = "comp";
}
2

2 Answers

1
votes

I think this will do what you want.

(\s+|^)(?<!-)[1-9][0-9,]*(\s+|$)

EDIT: I think I figured out your problem in your code. You're only checking based on Success property. You need to check answerMatch.Groups in your code as well.

If you checked answerMatch.Groups[0] when you enter 7+9 string, you will realize that the match only matches 7 and discards the rest (+9) of the string.

Ok, I have tested this more extensively and I'm sure that this now works. I've modified your code a little bit so I can use it to demonstrate my test.

        string testAnswer = "7 7+9700 700 007 400 -7 8";
        bool valid = true;
        string retVal = "";
        Regex answerRegex = new Regex(@"(\s+|^)(?<!-)[1-9][0-9,]*(\s+|$)");
        if (testAnswer.Contains(","))
        {
            testAnswer = testAnswer.Replace(",", "");
            retVal = testAnswer;
        }
        MatchCollection answerMatch = answerRegex.Matches(testAnswer.Trim());
        if (testAnswer == String.Empty || answerMatch.Count <= 0)
        {
            valid = false;
            retVal = "error";
        }           
        else
        {
            retVal = "comp";
            foreach(Match m in answerMatch) {
                Console.WriteLine(m.Groups[0].Value);
            }
        }

testAnswer holds my test string to be checked. The output of the test program is as follows:

7 
 700 
 400 
8

That output proves that it rejects negative numbers as well as special characters within the number string.

As for the regex string (\s+|^)(?<!-)[1-9][0-9,]*(\s+|$) here is the breakdown:

  • `(\s+|^) matches either the beginning of a string or leading whitespaces.
  • (?
  • [1-9][0-9,]* matches the numbers you are interested in including commas.
  • (\s+|$) matches either trailing whitespaces or end of the string.
0
votes

If I got you right it should be

Regex answerRegex = new Regex(@"^[1-9][0-9]*$");

The * instead of the + lets pass 1, 10, etc.