ferpega
ferpega

Reputation: 3224

Regex and C# to check range numbers + char (optional)

I am trying to check a valid Regex expression, with this class:

using System.Text.RegularExpressions;

namespace Checking
{
    public static class CheckALF
    {
        public static bool IsValueOk(string value)
        {
            Regex isValidNumber = new Regex(@"^\d{1,3}(?:I|D|R)?", RegexOptions.IgnoreCase);
            if (isValidNumber.IsMatch(value)) {
                return true;
            }
            return false;            
        }

    }
}

To facilitate regexp expression construct I use: http://www.radsoftware.com.au/regexdesigner/

But I have tried a lot of things that are running on 'regexdesigner' but not in C# .net 4 so I am a bit loss with this.

I put here the test code (only partially) with the failing test.

using Checking;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace TestCheck
{
    [TestClass]
    public class TestCheckALF
    {
        [TestMethod]
        public void Check_IsValid_OnlyNumbers_LessThan3Digits()
        {
            Assert.IsTrue(CheckALF.IsValueOk("40"));
            Assert.IsTrue(CheckALF.IsValueOk("0"));
            Assert.IsTrue(CheckALF.IsValueOk("999"));
        }

        [TestMethod]
        public void Check_IsValid_OnlyNumbersMoreThan3Digits()
        {
            Assert.IsFalse(CheckALF.IsValueOk("1000"));  //  ERROR.......
        }

        [TestMethod]
        public void Check_IsValid_NumbersAndR_LessThan3Digits()
        {
            Assert.IsTrue(CheckALF.IsValueOk("40R"));
            Assert.IsTrue(CheckALF.IsValueOk("0R"));
            Assert.IsTrue(CheckALF.IsValueOk("999R"));
        }

        [TestMethod]
        public void Check_IsValid_NumbersAndL_LessThan3Digits()
        {
            Assert.IsTrue(CheckALF.IsValueOk("40I"));
            Assert.IsTrue(CheckALF.IsValueOk("0i"));
            Assert.IsTrue(CheckALF.IsValueOk("999I"));
        }
    }
}

Thanks in advance.


Edit 2 (IMPORTANT)

RegExDesigner was failing expressions because the expression has a new line at the end. I mean:

^\d{1,3}(?:I|D|R)?
<new line>

But it fails as you can see in the second 'screenshot' below. And it has the right expression used in C# code, this one: ^\d{1,3}(?:I|D|R)?$

Edit 1

I copy here two screenshots from RegExDesigner:

First screenshot from RegExDesigner

Second screenshot from RegExDesigner -with Daniel advice-

Upvotes: 2

Views: 1502

Answers (1)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

You need to anchor the regex not only at the beginning but also at the end:

@"^\d{1,3}(?:I|D|R)?$"

Note the $ at the end of the expression.

1000 matches, because the first three digits match the expression. And without the missing anchor at the end, it is valid, that there are unmatching characters after that.

Upvotes: 4

Related Questions