[英]How to design regex pattern for number?
我正在研究正則表達式模式以驗證輸入,但我不確定如何包含()和 - 符號。
描述:不必填寫輸入字符串。 如果填寫它需要有5個數字,輸入不能以26開頭。此外,輸入需要接受括號和短划線,它們可以放在輸入的任何部分。 我接受最多10個字符
嘗試:
(^(?!26)((\d){5}))?
僅適用於: - 空輸入 - 正好十位數字,例如0123456789 - 如果您在開頭有26個,它也會拒絕,例如2651234567
此外,嘗試包括 - 和()但這種模式根本不起作用
(^(?!26)(\-\(\))((\d){5}))?
Valid inputs:
(12345)--
---12)567)
12333
-1-2--3-45
(()))12345
((12345
(-)65768-
(4)1-2-35
Invalid inputs:
26123---
(26)897---
-26333----
26
26(((())
26------
26--345
26)88-76
267-9
我發現討論一個全面的正則表達式用於電話號碼驗證 ,它有所幫助,但我仍然無法完全匹配我的條目。
你正在使用Java風格的正則表達式。 正確的正則表達式模式是:
^(?!26)([-()]*\\d){5}[-()]*$
這個將使你的輸入不能從26開始。但是,你的帖子沒有指定它是否可能像 - 2)6-218(它不是以26開頭,但前兩位是26。如果是這種情況,那么您需要:
^(?![-()]*2[-()]*6)([-()]*\\d){5}[-()]*$
最大10個字符應在輸入上驗證, maxlength=10
。
編輯:正如@ zx81指出的那樣,我有一些不必要的逃脫。 對不起,我不知道自己在想什么。 但是,此正則表達式模式不接受空字符串。
這個正則表達式會做你想要的(見演示 ):
^(?!\D*(?:26|555))(?=(?:\D*\d){5}\D*$)[\d()-]{5,10}$
如果你不想再拒絕555
,你可以選擇:
^(?!\D*26)(?=(?:\D*\d){5}\D*$)[\d()-]{5,10}$
如果不允許2--6123
,請將正則表達式更改為
^(?!\\D*2[()-]*6)(?=(?:\\D*\\d){5}\\D*$)[\\d()-]{5,10}$
解釋正則表達式
^ # the beginning of the string
(?! # look ahead to see if there is not:
\D* # non-digits (all but 0-9) (0 or more
# times (matching the most amount
# possible))
(?: # group, but do not capture:
26 # '26'
| # OR
555 # '555'
) # end of grouping
) # end of look-ahead
(?= # look ahead to see if there is:
(?: # group, but do not capture (5 times):
\D* # non-digits (all but 0-9) (0 or more
# times (matching the most amount
# possible))
\d # digits (0-9)
){5} # end of grouping
\D* # non-digits (all but 0-9) (0 or more
# times (matching the most amount
# possible))
$ # before an optional \n, and the end of
# the string
) # end of look-ahead
[\d()-]{5,10} # any character of: digits (0-9), '(', ')',
# '-' (between 5 and 10 times (matching the
# most amount possible))
$ # before an optional \n, and the end of the
# string
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.