Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

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

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.
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...