Character Sets & Quantifiers

! Content:Brackets []、Braces {}、Peratheses ()

Brackets [] - Character Sets

With a “character class”, also called “character set”, you can tell the regex engine to match only one out of several characters. Simply place the characters you want to match between square brackets []. 參考來源

1
2
3
4
5
6
7
re = /gr[ae]y/i  => Must be an a or e
re = /[GF]ray/ => Must be a G or F
re = /[^GF]ray/ => !! Match anything except a G or F
re = /[A-Z]ray/ => Match any Uppercase letter
re = /[a-z]ray/ => Match any Lowercase letter
re = /[A-Za-z]ray/ => Match any letter
re = /[0-9]ray/ => Match any digit; !!10ray符合

Curly Braces {} - Quantifiers

curly braces are used by a quantifier with specific limits

1
2
3
4
5
// the following are three different limits of [ l ]

re = /Hel{2}o/i => Must occur exactly {m} amount of times
re = /Hel{2,4}o/i // Must occur {m} amount of times based on numbers
re = /Hel{2,}o/i // Must occur at least {m} times

Peratheses () - Grouping

1
2
re = /([0-9]X){3}/ => 3 times
re = /^([0-9]X){3}$/