簡體   English   中英

用於日期驗證的正則表達式-解釋

[英]Regular Expression for date validation - Explain

我正在網上沖浪以進行日期驗證,但並不完全了解正則表達式。 有人可以解釋嗎? 我感到困惑? {}$ 我們為什么需要它們?

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}))$/;

? 表示“零或一個事件”。
{x} (其中x是數字)表示“恰好出現了x次”
$表示“行尾”

這些是非常基本的正則表達式,我建議您閱讀一些文檔

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

不建議為此使用正則表達式。 太多的極端情況和代碼變得難以維護。

^ = 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

總體而言,這是一個非常糟糕的表達方式。 我建議找到一個更好的,或使用一個實際的日期解析器。

表示“零或上述任何一項”

{n}表示“恰好是前述的n個”

$是字符串的結尾(感謝@Andy E)

簡要總結一下:

'?' 將匹配您放置在其前面的圖案組的0或1倍。 在這種情況下,可能會濫用它,應該將其排除在外,但這完全取決於您要匹配的內容。

“ {x}”告訴正則表達式與前面的模式組精確匹配x次。

$表示匹配行尾。

好:

^ // 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日期驗證的更多幫助,請參見: 僅捕獲日期的正則表達式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM