The start-of-line (^
) and end-of-line ($
) symbols are used in regular expressions to match the beginning and end of a line, respectively. While their behavior is consistent across many regex implementations, there can be subtle differences depending on the regex engine and settings.
General Usage:
- Start-of-line (
^
):- Matches the position at the start of a string or line.
- Example:
^Hello
matches “Hello” only if it appears at the start of the string or line.
- End-of-line (
$
):- Matches the position at the end of a string or line.
- Example:
world$
matches “world” only if it appears at the end of the string or line.
Behavior in Different Implementations:
1. Standard Behavior (Single-Line Mode)
- Most regex engines (e.g., Java, Python, JavaScript, etc.) treat
^
and$
as matching the start and end of the entire string by default. - Example:
- Regex:
^foo$
- Input:
"foo"
→ Matches the whole string. - Input:
"bar foo baz"
→ No match.
- Regex:
2. Multiline Mode (m
Flag)
- In multiline mode,
^
and$
match the start and end of each line in the string, not just the start and end of the entire string. - How to enable multiline mode:
- JavaScript: Use the
m
flag:/pattern/m
- Python: Pass
re.MULTILINE
tore.compile()
- Java: Use
(?m)
inline flag
- JavaScript: Use the
- Example:
- Regex:
^foo
- Input:
- Without multiline mode: Matches only the first
foo
at the start of the string. - With multiline mode: Matches both
foo
occurrences at the start of each line.
- Without multiline mode: Matches only the first
- Regex:
3. End-of-line and Trailing Newlines
- Some engines treat
$
as matching before a trailing newline (\n
) at the end of a string. - Example:
- Regex:
world$
- Input:
"hello world\n"
→ Matches “world” before the\n
.
- Regex:
- Use
\z
(or similar) in certain engines for an absolute end-of-string match.
Summary of Regex Engines:
Regex Engine | Single-line Default | Multiline Mode |
---|---|---|
JavaScript | ^ and $ match start/end of string |
/pattern/m flag enables line-by-line matching |
Python | Same as above | re.MULTILINE flag |
Java | Same as above | (?m) inline flag |
Perl | Same as above | /m modifier |
Ruby | Same as above | /m or /.../m flag |
Tips:
- Use
\A
for start-of-string and\z
for end-of-string in engines that support them (e.g., Python, Ruby, Java). - Always clarify if you need to match entire strings or line-by-line when crafting regex.