Chapter 12: Regular Expressions
Regular expressions (regex) are a powerful tool for pattern matching and text manipulation. They allow you to search for, match, and replace patterns in strings using a concise and flexible syntax. This chapter covers the basics of regular expressions, including pattern matching and validation techniques.
Introduction to Regular Expressions
A regular expression is a sequence of characters that forms a search pattern. Regular expressions can be used to perform various operations, such as searching, matching, and replacing text.
Basic Syntax
-
Literal Characters: Matches the exact characters in the string.
- Example:
/hello/matches "hello" in the string "hello world".
- Example:
-
Meta-Characters: Characters with special meanings.
.(Dot): Matches any single character except a newline.^(Caret): Matches the beginning of a string.$(Dollar): Matches the end of a string.*(Asterisk): Matches zero or more occurrences of the preceding element.+(Plus): Matches one or more occurrences of the preceding element.?(Question Mark): Matches zero or one occurrence of the preceding element.[](Square Brackets): Matches any one of the enclosed characters.|(Pipe): Acts as a logical OR between expressions.()(Parentheses): Groups expressions and captures matched text.
Example:
let pattern = /a.b/;
console.log(pattern.test("a_b")); // Output: true
Flags
Flags modify the behavior of regular expressions:
i: Case-insensitive matching.g: Global search (matches all occurrences).m: Multiline matching (affects^and$).
Example:
let pattern = /hello/i; // Case-insensitive match
console.log(pattern.test("Hello")); // Output: true
Pattern Matching and Validation
Regular expressions are commonly used for pattern matching and validation of input. Here are some common use cases:
Matching Patterns
1. Matching a Specific Word
Matches the exact word "hello" in a string.
Example:
let pattern = /hello/;
console.log(pattern.test("hello world")); // Output: true
console.log(pattern.test("hi there")); // Output: false
2. Matching Any Digit
Matches any single digit from 0 to 9.
Example:
let pattern = /\d/;
console.log(pattern.test("123abc")); // Output: true
console.log(pattern.test("abc")); // Output: false
3. Matching a Range of Characters
Matches any letter from 'a' to 'f'.
Example:
let pattern = /[a-f]/;
console.log(pattern.test("abcdef")); // Output: true
console.log(pattern.test("ghijkl")); // Output: false
Validation
Regular expressions are often used to validate input, such as email addresses, phone numbers, and passwords.
1. Validating an Email Address
A simple regex pattern to validate an email address.
Example:
let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
console.log(emailPattern.test("example@example.com")); // Output: true
console.log(emailPattern.test("invalid-email")); // Output: false
2. Validating a Phone Number
A pattern to validate a phone number with optional area code.
Example:
let phonePattern = /^(\+?\d{1,3})?(\d{10})$/;
console.log(phonePattern.test("+1234567890")); // Output: true
console.log(phonePattern.test("1234567890")); // Output: true
console.log(phonePattern.test("123-456-7890")); // Output: false
3. Validating a Password
A pattern to validate a password that must be at least 8 characters long and include at least one uppercase letter, one lowercase letter, one digit, and one special character.
Example:
let passwordPattern =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
console.log(passwordPattern.test("Password1!")); // Output: true
console.log(passwordPattern.test("password")); // Output: false
Common Methods
Regular expressions in JavaScript can be used with several methods to search and manipulate strings:
1. test()
Tests if a pattern matches a string and returns true or false.
Syntax:
regex.test(string);
Example:
let pattern = /hello/;
console.log(pattern.test("hello world")); // Output: true
2. exec()
Executes a search for a match in a string and returns an array of information or null if no match is found.
Syntax:
regex.exec(string);
Example:
let pattern = /(\d+)/;
let result = pattern.exec("There are 123 apples");
console.log(result[0]); // Output: '123'
console.log(result[1]); // Output: '123'
3. match()
Searches a string for a match to a regular expression and returns an array of results or null if no match is found.
Syntax:
string.match(regex);
Example:
let text = "The price is $100";
let result = text.match(/\d+/);
console.log(result[0]); // Output: '100'
4. replace()
Searches a string for a match to a regular expression and replaces the matched substring with a new string.
Syntax:
string.replace(regex, replacement);
Example:
let text = "Hello John Doe";
let result = text.replace(/John/, "Jane");
console.log(result); // Output: 'Hello Jane Doe'
5. split()
Splits a string into an array of substrings based on a regular expression.
Syntax:
string.split(regex);
Example:
let text = "apple,banana,grape";
let result = text.split(/,/);
console.log(result); // Output: ['apple', 'banana', 'grape']