What is the difference between square brackets and parentheses in a regex? Ask Question

What is the difference between square brackets and parentheses in a regex? Ask Question

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}$/

The rule is to validate a phone number:

  • It should be of only ten numbers.
  • The first number is supposed to be any of 7, 8 or 9.

ベストアンサー1

These regexes are equivalent (for matching purposes):

  • /^(7|8|9)\d{9}$/
  • /^[789]\d{9}$/
  • /^[7-9]\d{9}$/

The explanation:

  • (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] is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d] = [abcd])

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.

おすすめ記事