views:

219

answers:

5

In C#, I want to write a regular expression that will accept only years between 1900 and 2099.

I tried ^([1][9]\d\d|[2][0]\d\d)$, but this does not work. Any ideas?

So i have in a class:

    [NotNullValidator(MessageTemplate = "Anul nu poate sa lipseasca!")]
  //  [RangeValidator(1900, RangeBoundaryType.Inclusive, 2100, RangeBoundaryType.Inclusive, MessageTemplate = "Anul trebuie sa contina 4 caractere!")]
    [RegexValidator(@"(19|20)\d{2}$", MessageTemplate = "Anul trebuie sa fie valid!", Ruleset = "validare_an")]
    public int anStart
    {
        get;
        set;
    }

And in a test method:

[TestMethod()]
public void anStartTest()
{
    AnUnivBO target = new AnUnivBO() { anStart = 2009 };
    ValidationResults vr = Validation.Validate<AnUnivBO>(target, "validare_an");
    Assert.IsTrue(vr.IsValid);
}

Why it fails?

+2  A: 

You should leave out the [], for those are indicators for character classes

/^(19\d\d|20\d\d)$/

also, regexes are slow. using if(date <= 2099 && date>=1900) is much faster

The Guy Of Doom
-(-1). Now, about that "regexes are slow" comment... :D
Alan Moore
+3  A: 

Try this:

^(19|20)\d{2}$
Rubens Farias
Also a valid answer. `{2}` means: look for two of these.
The Guy Of Doom
A: 

Try this:

^((19\d\d)|(20\d\d))$

liwp
-1 copycat. Thats my answer :@ and I was an hour earlier
The Guy Of Doom
@TGOD: If this were a copy of your answer, it would contain the sequence `/d`, which matches a forward-slash followed by the letter 'd'. But as you can see, this answer contains `\d`, the escape sequence for a digit. Which, now I think about, will probably work a little better, don't you think? :@
Alan Moore
ok thats true :$
The Guy Of Doom
A: 

In Python, ^(19|20)\d\d$ works.

>>> import re
>>> pat=re.compile("^(19|20)\\d\\d$")
>>> print re.match(pat,'1999')
<_sre.SRE_Match object at 0xb7c714a0>
>>> print re.match(pat,'2099')
<_sre.SRE_Match object at 0xb7c714a0>
>>> print re.match(pat,'1899')
None
>>> print re.match(pat,'2199')
None
>>> print re.match(pat,'21AA')
None
MAK
+2  A: 

You need to use a string property, not an integer, for the RegexValidator to work:

public string anStart
{
    get;
    set;
}

In your test method you would need to use:

AnUnivBO target = new AnUnivBO() { anStart = "2009" };

To continue using an integer use a RangeValidator:

[RangeValidator(1900, RangeBoundaryType.Inclusive,
                2099, RangeBoundaryType.Inclusive)]
public anStartint anStart 
{
   get; set;
)
Ahmad Mageed
And if i wanna use anStart as an integer, and validate it being between 1900 and 2099 what should i use? RangeValidator?
qwerty
@qwerty: yes, updating...
Ahmad Mageed