Groups and Ranges in JavaScript Regular Expressions (Live Playground)
Groups and ranges in JavaScript regular expressions allow you to organize and match multiple characters in a pattern. In this tutorial, we'll explore different types of groups and ranges and how to use them.
Character Groups
A character group is a set of characters enclosed in square brackets [ ]
. It matches any single character within the group:
const vowels = /[aeiou]/; // matches any vowel (a, e, i, o, or u)
Negated Character Groups
To match any character not in a group, use a caret symbol ^
at the beginning of the group:
const consonants = /[^aeiou]/; // matches any consonant (not a, e, i, o, or u)
Ranges
Within a character group, you can specify a range of characters with a hyphen -
. For example, you can match all lowercase letters using the range a-z
:
const lowercaseLetters = /[a-z]/; // matches any lowercase letter
You can also combine multiple ranges and individual characters in a single group:
const alphanumeric = /[A-Za-z0-9]/; // matches any uppercase letter, lowercase letter, or digit
Capturing Groups
Capturing groups, enclosed in parentheses ( )
, allow you to group together and capture part of a pattern:
const datePattern = /(\d{4})-(\d{2})-(\d{2})/; // captures the year, month, and day in a YYYY-MM-DD date format
Non-Capturing Groups
To create a non-capturing group, use the syntax (?: )
. This allows you to group elements without capturing the matched text:
const nonCapturing = /(?:abc){2}/; // matches 'abcabc' but does not capture the individual 'abc' instances
Conclusion
Groups and ranges in JavaScript regular expressions help you organize and match multiple characters in a pattern. We covered character groups, negated character groups, ranges, capturing groups, and non-capturing groups. Understanding how to use groups and ranges effectively will help you create more precise and powerful regular expressions.