Regular Expressions
Regular Expressions:
Algorithms of regular match or regex or regexp in Javascript are powerful tools for matching and string transformation.
They offer an optimal approach to define, locate, and access text patterns in a compact and adaptable manner.
Creating Regular Expressions:
You can create a regular expression using the RegExp constructor or a literal syntax enclosed in slashes (/pattern/).
Using RegExp constructor:
const regex = new RegExp('pattern');
Literal Syntax:
const regexLiteral = /pattern/;
Basic Patterns:
Characters:
A regular expression can consist of literal characters, such as /abc/ to match the sequence "abc."
Quantifiers:
Quantifiers specify how many occurrences of a character or group are expected.
Examples:
- *: Zero or more occurrences
- +: One or more occurrences
- ?: Zero or one occurrence
- {n}: Exactly n occurrences
- {n,}: n or more occurrences
- {n,m}: Between n and m occurrences
Character Classes:
Character classes allow you to match any one of a set of characters.
Square Brackets:
- [abc]: Matches any one of the characters a, b, or c.
- [^abc]: Matches any character except a, b, or c.
Anchors:
Anchors are used to match positions in the string rather than characters.
- ^: Matches the start of a string.
- $: Matches the end of a string.
Modifiers:
i (case-insensitive):
- /pattern/i makes the pattern case-insensitive.
Metacharacters:
\ (backslash):
- Escapes a metacharacter, treating it as a literal character.
Example Usage:
const text = "Hello, this is a sample text with some patterns.";
const pattern = /pattern/;
console.log(pattern.test(text)); // Output: true
console.log(text.match(pattern)); // Output: ['pattern']
Test Regular Expressions Online:
You can test and experiment with regular expressions using online tools like RegExr or Regex101.