Regular Expressions Explained
Key Concepts
- Pattern Matching
- Character Classes
- Quantifiers
- Anchors
- Groups and Backreferences
Pattern Matching
Pattern matching is the core concept of regular expressions, where a specific pattern is defined to search for within a string. This pattern can be a simple sequence of characters or a complex combination of characters and special symbols.
Example:
let pattern = /hello/; let text = "hello world"; console.log(pattern.test(text)); // Outputs: true
Character Classes
Character classes allow you to define a set of characters that can match at a given point in the pattern. Common character classes include [abc]
(matches any one of 'a', 'b', or 'c'), \d
(matches any digit), and \w
(matches any word character).
Example:
let pattern = /[aeiou]/; let text = "hello"; console.log(pattern.test(text)); // Outputs: true
Quantifiers
Quantifiers specify how many instances of a character, group, or character class must be present in the input for a match to be found. Common quantifiers include *
(zero or more), +
(one or more), and ?
(zero or one).
Example:
let pattern = /go*d/; let text = "good"; console.log(pattern.test(text)); // Outputs: true
Anchors
Anchors are used to specify the position of the pattern within the string. Common anchors include ^
(start of the string) and $
(end of the string).
Example:
let pattern = /^hello$/; let text = "hello"; console.log(pattern.test(text)); // Outputs: true
Groups and Backreferences
Groups allow you to treat multiple characters as a single unit. Backreferences allow you to refer to a previously matched group within the same regular expression. Groups are created using parentheses ()
, and backreferences are denoted by \1
, \2
, etc.
Example:
let pattern = /(\w+)\s\1/; let text = "hello hello"; console.log(pattern.test(text)); // Outputs: true