About Lesson
What is Regex?
Regular expressions (regex) are patterns used to match sequences of characters in strings. They are powerful tools for searching, validating, and manipulating text.
Creating a Regex:
1. Literal Syntax:
Regex patterns are written between slashes (/pattern/).
Syntax: (/pattern/).
2. Constructor Syntax:
Use the RegExp constructor to create a regex.
Syntax: let regex = new RegExp(“hello”);
Special Characters in Regex:
1. Anchors:
- ^: Matches the beginning of a string.
- $: Matches the end of a string.
JavaScript
let regex = /^hello/; // Matches "hello" only if it’s at the start.
console.log(regex.test("hello world")); // true
console.log(regex.test("world hello")); // false
2. Character Classes:
- .: Matches any single character except a newline.
- \d: Matches any digit (0-9).
- \w: Matches any word character (alphanumeric + underscore).
- \s: Matches any whitespace character (space, tab).
- \D, \W, \S: Match the opposite of \d, \w, and \s.
JavaScript
let regex = /\d/; // Matches any digit.
console.log(regex.test("abc123")); // true
3. Quantifiers:
- *: Matches 0 or more occurrences.
- +: Matches 1 or more occurrences.
- ?: Matches 0 or 1 occurrence.
- {n}: Matches exactly n occurrences.
- {n,}: Matches at least n occurrences.
- {n,m}: Matches between n and m occurrences.
JavaScript
let regex = /a{2,4}/; // Matches "aa", "aaa", or "aaaa".
console.log(regex.test("aaa")); // true
4. Groups and Ranges:
- (abc): Matches the exact group abc.
- [a-z]: Matches any character in the range a to z.
- [^a-z]: Matches any character NOT in the range a to z.
JavaScript
let regex = /[A-Z]/; // Matches any uppercase letter.
console.log(regex.test("Hello")); // true
5. Escaping Special Characters:
- Use \ to escape special characters like ., *, ?, etc.
JavaScript
let regex = /\./; // Matches a literal dot.
console.log(regex.test("1.23")); // true