2011-03-29 71 views
0

我在線上網進行日期驗證,但沒有完全理解正則表達式。任何人都可以解釋嗎?我很困惑?,{}$。我們爲什麼需要它們?日期驗證的正則表達式 - 說明

dateReg = /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/; 
+0

你從哪裏得到的?這是我見過的最糟糕的正則表達式之一。 – 2011-03-29 15:13:35

回答

2
^ = beginning of the string 
[0,1]? = optional zero, one or comma (the comma is probably an error) 
\d{1} = exactly one digit (the {1} is redundant) 
\/ = a forward slash 
[0-2]? = optional zero, one or two (range character class) followed by any single digit (\d{1}) 
OR [3] = three (character class redundant here) followed by exactly one zero, one or comma 
\/ = forward slash 
[1]{1}[9]{1}[9]{1}\d{1} = 199 followed by any digit 
OR 2-9 followed by any 3 digits 

總的來說,這是一個寫得很差的表達。我建議找一個更好的,或使用真正的日期解析器。

1

?的意思是「零或上述中的一個」

{N}表示「恰好n的上述」

$是字符串的結尾(由於@Andy E)

+0

'{n}'表示*「正好是前面提到的n」*。 '{0,n}'將會是*「達到上述」*的n「。 '$'是字符串的結尾,除非使用'm'開關。 – 2011-03-29 15:02:45

+0

@安迪謝謝!我記得剛剛提交的第一個事實;) – 2011-03-29 15:04:28

3

?意思是「零或一個發生「。
{x}(其中x是一個數字)的意思是「精確的x OCCURENCES」
$的意思是「行結束」

這些都是很基本的正則表達式,我推薦你讀some documentation

1

簡要總結一下:

'?'將匹配您放在它前面的模式組的0或1倍。在這種情況下,它可能被濫用,應該排除在外,但這一切都取決於您想要匹配的內容。

`{x}'告訴正則表達式正好x次匹配前面的模式組。

`$'表示匹配行的末尾。

+0

沒關係,我現在看到他們想要匹配什麼:'?'這裏需要。 – 2011-03-29 15:05:42

1

好:

^ // start of the text 
$ // end of the text 
X{n} // number n inside these curly parenthesis define how many exact occurrences of X 
X{m,n} // between m to n occurrences of X 
X? // 0 or 1 occurrence of X 
\d // any digits 0-9 

有關的Javascript日期驗證詳細說明,請參閱:Regular Expression to only grab date

2

在Javascript中,你可以通過它傳遞給Date.Parse()函數驗證日期。成功轉換爲日期對象意味着您擁有有效的日期。

不建議使用正則表達式。邊緣案例太多,代碼難以維護。