正则表达式中的方括号和圆括号有什么区别? [英] What is the difference between square brackets and parentheses in a regex?

查看:74
本文介绍了正则表达式中的方括号和圆括号有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我创建的用于 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.

这篇关于正则表达式中的方括号和圆括号有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆