Skip to content

Trouble with C# and regular expressions

Bjarni

Asked Feb 21, 2007, 12:59 AM EST2 answers
Share
LinkedInX
Hi, I am trying to use regular expression to check if a string is a number and I do not want leading zeros so "123" is legal but "0123" is not and I am using the following: Regex objNaturalPattern = new Regex("[1-9][0-9]*"); This works fine detecting if it is a number or alpha but it always gives me true for leading zeros, how can I make the zeros in front give me a false? Thanks

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Mike Gold
    0
    try

    Regex exp = new Regex("^[1-9][0-9]*");

    0
  • 0
    Thanks that worked, but now I have another question if I want the string that I am testing to be of a certain length how does that work, I was trying: Regex regex = new Regex("^[1-9][0-9]{0,5}"); where {0,5} should allow the string to be 0 to 5 digits long but that does not work for me. Any ideas. Does anyone know of a good place to read about C# regex. It seems to me that diffrent characters have diffrent meaning in different programming languages. BR
    0