2010-01-23 31 views
3

在C#中的時間間隔,我想寫一個正則表達式,將接受1900年和2099年正則表達式的年

我試圖^([1][9]\d\d|[2][0]\d\d)$之間只有幾年,但不起作用。有任何想法嗎?

所以我有一個類:

[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; 
    } 

而且在測試方法:

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

爲什麼失敗?

+0

你的模式是有效的,雖然它可以縮短。請張貼一些示例代碼,說明你如何使用它來說明爲什麼它不適合你。 – 2010-01-23 20:39:33

回答

2

你需要使用一個字符串屬性,而不是一個整數,對於RegexValidator工作:

public string anStart 
{ 
    get; 
    set; 
} 

在您的測試方法,你將需要使用:

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

要繼續使用整數使用a RangeValidator

[RangeValidator(1900, RangeBoundaryType.Inclusive, 
       2099, RangeBoundaryType.Inclusive)] 
public anStartint anStart 
{ 
    get; set; 
) 
+0

如果我想使用一個整數作爲一個整數,並驗證它在1900年和2099年之間我應該使用什麼? RangeValidator控件? – qwerty 2010-01-23 20:51:31

+0

@qwerty:是的,正在更新... – 2010-01-23 20:53:05

2

你應該離開了[],對於那些指標字符類

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

也,正則表達式是緩慢的。使用if(date <= 2099 && date>=1900)快得多

+0

- ( - 1)。現在,關於「正則表達式很慢」的評論...:D – 2010-02-14 20:00:16

3

試試這個:

^(19|20)\d{2}$ 
+0

也是一個有效的答案。 '{2}'表示:查找其中的兩個。 – 2010-01-23 20:36:36

0

試試這個:

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

+1

-1模仿。這就是我的答案:@和我早一個小時 – 2010-01-23 21:33:44

+1

@TGOD:如果這是你的答案的副本,它將包含序列'/ d',它匹配正斜槓後跟字母'd'。但正如你所看到的,這個答案包含了一個數字的轉義序列'\ d'。現在我想,這可能會更好一些,你不覺得嗎? :@ – 2010-01-24 02:27:16

+0

好吧那是真的:$ – 2010-02-14 16:03:42

0

在Python,^(19|20)\d\d$的作品。

>>> 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 
相關問題