我正在尝试验证 Firebase 事件名称:
事件名称最长可达 40 个字符,只能包含字母数字字符和下划线("_"),必须以字母字符开头。
无效:
4foo
(以数字开头)foo bar
(包含空格)foo$@bar
(包含特殊字符)
有效:
foo
foo_bar
Foo_Bar
我尝试使用 \d?[^A-Za-z0-9_]+
进行匹配,如果有任何特殊字符和空格,则匹配成功,但它无法匹配以数字字符开头的字符串。
我正在尝试验证 Firebase 事件名称:
事件名称最长可达 40 个字符,只能包含字母数字字符和下划线("_"),必须以字母字符开头。
无效:
4foo
(以数字开头)foo bar
(包含空格)foo$@bar
(包含特殊字符)有效:
foo
foo_bar
Foo_Bar
我尝试使用 \d?[^A-Za-z0-9_]+
进行匹配,如果有任何特殊字符和空格,则匹配成功,但它无法匹配以数字字符开头的字符串。
使用
^[A-Za-z][A-Za-z0-9_]{0,39}$
请参考正则表达式证明。
同义词:
^[A-Za-z]\w{0,39}$
^\p{L}\w{0,39}$
^[[:alpha:]]\w{0,39}$
解释
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
[A-Za-z] any character of: 'A' to 'Z', 'a' to 'z'
--------------------------------------------------------------------------------
[A-Za-z0-9_]{0,39} any character of: 'A' to 'Z', 'a' to 'z',
'0' to '9', '_' (between 0 and 39 times
(matching the most amount possible))
--------------------------------------------------------------------------------
$ before an optional \n, and the end of the
string
/^(?=[a-z].{39}$)(?=\w+$).+$/i
^[a-zA-Z]\w+$
这个怎么样? - Lieven Keersmaekers^[A-Za-z]\w{0,39}$
的表达式应该可以吗? - JvdV^[a-zA-Z]\w+$
和^[A-Za-z]\w{0,39}$
都可以工作,请将它们作为答案写下来,谢谢。 - Trong Nguyen