[英]How to write a regex expression to check a valid XML element NCName in javascript?
NCNam表示它必须以字母或下划线开头,并且只能包含字母,数字,下划线,连字符和句点。我试图这样写正则表达式,但我认为可能是错误的。
if(/^([_]|[a-zA-Z]+[\w\W])$/.test('abc' )) console.log('match')
Your ^([_]|[a-zA-Z]+[\\w\\W])$
pattern matches a string that is either equal to _
( [_]
) or ( |
) is formed of 1+ letters ( [a-zA-Z]+
) followed with any char ( [\\w\\W]
). 您的
^([_]|[a-zA-Z]+[\\w\\W])$
模式匹配一个等于_
( [_]
)或( |
)的字符串,该字符串由1+个字母组成( [a-zA-Z]+
)后跟任意字符( [\\w\\W]
)。 So, it cannot validate the strings of the type you mention. 因此,它无法验证您提到的类型的字符串。
You may use 您可以使用
/^[a-zA-Z_][\w.-]*$/
See the regex demo and the graph ( source ) below: 请参阅正则表达式演示和下面的图( 源 ):
Details 细节
^
- start of string ^
-字符串开头 [a-zA-Z_]
- a letter or _
[a-zA-Z_]
-字母或_
[\\w.-]*
- 0 or more letters, digits, underscores, dots or hyphens [\\w.-]*
-0或更多字母,数字,下划线,点或连字符 $
- end of string $
-字符串结尾 must start with a letter or underscore
必须以字母或下划线开头
Match the first character with [a-z_]
将第一个字符与
[a-z_]
匹配
and can only contain letters, digits, underscores, hyphens, and periods
并且只能包含字母,数字,下划线,连字符和句点
Use a character class containing all of those. 使用包含所有这些字符类。 Note that letters, digits, and underscores together make up the representation of a "word character", so you can use
\\w
instead of writing those out separately. 请注意,字母,数字和下划线共同构成了“单词字符”的表示形式,因此您可以使用
\\w
而不是分别写出来。
In full: 在全:
/^[a-z_][\w.-]*$/i
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.