regex for interval of years
In C#, I want to write a regul开发者_运维技巧ar 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?
Try this:
^(19|20)\d{2}$
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;
)
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
Try this:
^((19\d\d)|(20\d\d))$
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
精彩评论