正则表达式中的方括号和圆括号有什么区别?
这是我创建的用于 JavaScript 的正则表达式:
Here is a regular expression I created to use in JavaScript:
var reg_num = /^(7|8|9)\d{9}$/
这是我的团队成员推荐的另一个.
Here is another one suggested by my team member.
var reg_num = /^[7|8|9][\d]{9}$/
规则是验证电话号码:
- 它应该只有十个数字.
- 第一个数字应该是 7、8 或 9 中的任何一个.
这些正则表达式是等效的(用于匹配目的):
These regexes are equivalent (for matching purposes):
/^(7|8|9)\d{9}$/
/^[789]\d{9}$/
/^[7-9]\d{9}$/
说明:
(a|b|c)
是一个正则表达式OR",意思是a 或 b 或 c",虽然括号的存在是 OR 所必需的,也是 捕获数字.为了严格等效,您可以编码(?:7|8|9)
以使其成为非捕获组.
(a|b|c)
is a regex "OR" and means "a or b or c", although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code(?:7|8|9)
to make it a non capturing group.
[abc]
是一个字符类",意思是来自 a、b 或 c 的任何字符"(字符类可以使用范围,例如 [ad]
= [abcd]
)
[abc]
is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d]
= [abcd]
)
这些正则表达式相似的原因是字符类是或"的简写(但仅适用于单个字符).或者,您还可以执行诸如 (abc|def)
之类的操作,它不会转换为字符类.
The reason these regexes are similar is that a character class is a shorthand for an "or" (but only for single characters). In an alternation, you can also do something like (abc|def)
which does not translate to a character class.