Modifiers in Regular Expressions
1. Case Insensitivity (i)
The i
modifier makes the regular expression case-insensitive. This means that the pattern will match regardless of whether the letters are uppercase or lowercase.
Example:
Pattern: /hello/i
Matches: "hello", "Hello", "HELLO"
Explanation: The pattern matches any variation of "hello" regardless of case.
2. Global Search (g)
The g
modifier performs a global match, meaning it finds all matches in the string rather than stopping after the first match.
Example:
Pattern: /the/g
Text: "The quick brown fox jumps over the lazy dog."
Matches: "The", "the"
Explanation: The pattern finds all instances of "the" in the text.
3. Multiline Mode (m)
The m
modifier enables multiline mode, where the ^
and $
anchors match the start and end of each line (instead of the start and end of the entire string).
Example:
Pattern: /^The/m
Text: "The quick brown fox\njumps over the lazy dog."
Matches: "The" at the start of the first line
Explanation: The pattern matches "The" only at the start of each line.
4. Dot All (s)
The s
modifier allows the dot .
to match newline characters. Normally, the dot matches any character except newline.
Example:
Pattern: /a.b/s
Text: "a\nb"
Matches: "a\nb"
Explanation: The pattern matches "a" followed by any character (including newline) and then "b".
5. Unicode (u)
The u
modifier enables full Unicode matching. This is particularly useful for matching characters outside the basic multilingual plane.
Example:
Pattern: /\u{1F600}/u
Text: "😀"
Matches: "😀"
Explanation: The pattern matches the Unicode character U+1F600 (grinning face).
6. Sticky (y)
The y
modifier performs a sticky search that matches starting at the current position in the target string. It ensures that the match is found only at the specified position.
Example:
Pattern: /foo/y
with lastIndex set to 3
Text: "barfoobar"
Matches: "foo" starting at index 3
Explanation: The pattern matches "foo" only if it starts at the specified index.
7. Ignore Whitespace (x)
The x
modifier allows you to include whitespace and comments in the regular expression for better readability. It ignores unescaped whitespace and treats # as a comment.
Example:
Pattern: /hello # match hello\nworld # match world/x
Text: "hello world"
Matches: "hello", "world"
Explanation: The pattern matches "hello" and "world" with comments and whitespace for readability.