[英]What is regex for alphanumeric with no spaces?
我需要這樣匹配:
1. 1234 true
2. 1234 5678 false
3. 1234x true
4. x1234 true
5. abcd false
6. abcd 1234 false
所以我只需要匹配一個僅包含數字或僅包含數字和字符且沒有空格(單個單詞)的字符串。 這實際上不起作用:
/([0-9])\w+/g
您的模式([0-9])\w+
未錨定,因此它可以有部分匹配。
它還必須以數字開頭,至少 1 個單詞字符,字符串長度至少為 2 個字符。
您可以使用錨點,並確保匹配單個數字。 僅對於匹配,您可以省略捕獲組:
^[^\W\d]*\d\w*$
^
字符串開始[^\W\d]*
可選擇匹配除數字以外的任何單詞字符\d
匹配單個數字\w*
匹配可選的單詞字符$
字符串結尾注意\w
也可以匹配_
匹配整個字符串並需要至少一位數字:
/^[a-z]*[0-9][a-z0-9]*$/i
請參閱正則表達式證明。 重要: i
標志(不區分大小寫)。
解釋
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
[a-z]* any character of: 'a' to 'z', 'A' to 'Z' (0 or more
times (matching the most amount possible))
--------------------------------------------------------------------------------
[0-9] any character of: '0' to '9'
--------------------------------------------------------------------------------
[a-z0-9]* any character of: 'a' to 'z', 'A' to 'Z', '0' to '9'
(0 or more times (matching the most amount
possible))
--------------------------------------------------------------------------------
$ the end of the string
const strings = ['1234','12x3', '12 X']; console.log(strings.filter(string=> string.match(/^[0-9a-z]+$/i)));
正則表達式: /^[0-9a-zA-Z]+$/
使用test
得到 boolean 結果; 使用match
獲取匹配的字符串
const result = ['1234', '1234 5678', '1234x', 'x1234', 'abcd', 'abcd 1234'].map(str=> /^[0-9a-zA-Z]+$/.test(str)) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.