[英]Regular Expression only digits and blank spaces
我有一個文本輸入,我要求它只接受數字(0-9)和空格(“”)。 驗證此輸入的當前正則表達式是:
/((\d{1,})(\s{1,})?){1,}/
它代表:一個或多個組基於一個或多個數字的第一組和一個或多個空格的可選第二組
這只會讓我將值引入: 999999
(僅數字)或" "
(僅空格)或91 08 8510 903
(數字和空格的混合)。 但實際上,我也可以插入aaa
或其他字符。
您的正則表達式不接受字母:
/((\d{1,})(\s{1,})?){1,}/.test('aaa') // false
實際上,如果輸入包含至少一個數字,則接受任何字符:
/((\d{1,})(\s{1,})?){1,}/.test('a1a') // true
話雖這么說,讓我們從你的模式中撇開脂肪:
"{1,}" equals "+" -> ((\d+)(\s+)?)+
"(.+)?" equals ".*" -> ((\d+)\s*)+
useless brackets -> (\d+\s*)+
此結果可以轉換為:“一個或多個數字( \\d+
)后跟零個或多個空格( \\s*
),一次或多次( ()+
), 輸入中的任何位置 ”。 或者,我們可以說:“ 輸入中的任何位置至少有一個數字”。
您需要的是將“輸入中的任何位置”替換為“從輸入的開頭到結尾”。 這由以下特殊字符允許: ^
(輸入開始)和$
(輸入結束)。 讓我們做一堆測試,看看它們是如何工作的:
requirement regex input .test()
---------------------------------------------------------------------
must contain at least one digit /\d+/ 'a1a' true
must start with at least one digit /^\d+/ '1a' true
must start with at least one digit /^\d+/ 'a1' false
must end with at least one digit /\d+$/ '1a' false
must end with at least one digit /\d+$/ 'a1' true
only digits from the beginning to the end /^\d+$/ '1a1' false
只有可能由一個空格分隔的數字: /^\\d+( \\d+)*$/
。
^ beginning of the input
\d+ a digit, one or more times
( \d+)* a whitespace + same as above, zero or more times
$ end of the input
用法示例:
var r = /^\d+( \d+)*$/;
var isValid = r.test(' 1 '); // false
var isValid = r.test('1 1'); // true
var isValid = r.test('1 1'); // false
有關正則表達式的更多信息: http : //www.javascriptkit.com/javatutors/redev.shtml 。
試試這個
$pattern = '/^[0-9 ]+$/';
if ( preg_match ($pattern, $text) )
{
echo 'allowed';
}
試試這個正則表達式
/(\d+\s*\d*)+$/
在http://regex101.com/r/dE5uR8可視化結果
我已經在線測試了它
上面的正則表達式在開始時不接受空的空格。 你需要至少一位數。 如果你想在開始時匹配空格,也把它改成(\\ d * \\ s * \\ d *)+ $,它也會接受空格
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.