string manipulation
substring extraction
programming tutorial
coding tips
text processing

How to get a string after a specific substring?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

Extracting text after a specific substring is a common parsing task in logs, URLs, and config strings. The implementation looks simple, but edge cases like missing delimiter and repeated delimiter often cause bugs. A robust approach should define expected behavior clearly before writing code.

Python Approaches That Are Safe and Readable

Python offers several clean methods for this task. partition is often the safest because it always returns a three part tuple.

python
1text = "order_id=5291;status=paid"
2_, sep, tail = text.partition("order_id=")
3result = tail if sep else ""
4print(result)  # 5291;status=paid

If delimiter is absent, sep is empty so you can branch safely.

Another option is split with max split count:

python
1text = "prefix::value::extra"
2parts = text.split("::", 1)
3result = parts[1] if len(parts) == 2 else ""
4print(result)  # value::extra

Use max split equal to one when you want content after first occurrence.

Extract After Last Occurrence

Sometimes you need content after the last occurrence of delimiter, such as filename after final slash.

python
1path = "logs/2026/03/app.log"
2head, sep, tail = path.rpartition("/")
3result = tail if sep else path
4print(result)  # app.log

rpartition is ideal for this case because it scans from right side and keeps logic explicit.

Regular Expressions for Pattern Based Delimiters

If delimiter logic depends on pattern rather than fixed text, regex can help.

python
1import re
2
3text = "id: 42 | name: Alice | role: admin"
4m = re.search(r"name:\s*(.*)$", text)
5print(m.group(1) if m else "")

Regex is powerful but should be used only when fixed substring methods are insufficient.

API Design for Reuse

Wrap extraction logic in a utility function with explicit defaults. This avoids repeated ad hoc code across services.

python
1def after_substring(s: str, marker: str, default: str = "") -> str:
2    if marker == "":
3        raise ValueError("marker must not be empty")
4    parts = s.split(marker, 1)
5    return parts[1] if len(parts) == 2 else default
6
7print(after_substring("token=abc123", "token="))
8print(after_substring("missing", "token=", default="none"))

Unit tests should cover missing marker, empty marker, and multiple marker appearances.

Cross Language Patterns and Performance Notes

The same extraction idea appears in many languages. Knowing equivalent methods helps when you maintain mixed stacks.

JavaScript example:

javascript
1const text = "token=abc123&mode=prod";
2const marker = "token=";
3const idx = text.indexOf(marker);
4const result = idx >= 0 ? text.slice(idx + marker.length) : "";
5console.log(result);

C# example:

csharp
1string text = "token=abc123&mode=prod";
2string marker = "token=";
3int idx = text.IndexOf(marker, StringComparison.Ordinal);
4string result = idx >= 0 ? text[(idx + marker.Length)..] : string.Empty;
5Console.WriteLine(result);

For large log files, avoid repeatedly scanning long strings when marker position can be cached or when parser state can be streamed line by line. Also normalize encoding and whitespace early so substring extraction behavior is consistent across input sources.

Build Tests for Ambiguous Input

Extraction bugs usually appear with ambiguous content. Include tests for repeated markers, delimiter at end of string, and Unicode text.

python
1cases = [
2    ("a=1|b=2", "a=", "1|b=2"),
3    ("a=", "a=", ""),
4    ("no marker", "a=", ""),
5]
6
7for s, marker, expected in cases:
8    assert after_substring(s, marker) == expected

Common Pitfalls

  • Assuming delimiter always exists and indexing split result directly.
  • Using full regex parsing for simple fixed delimiters.
  • Forgetting to specify first or last occurrence requirements.
  • Ignoring whitespace normalization after extraction.
  • Not handling empty marker input in utility functions.

Summary

  • Use partition or split for fixed delimiter extraction.
  • Use rpartition when last occurrence logic is required.
  • Add defaults for missing delimiter cases to avoid crashes.
  • Reserve regex for pattern based extraction needs.
  • Centralize helper logic and test edge cases thoroughly.
  • Document delimiter assumptions in parser code so future maintainers preserve expected extraction semantics when input formats evolve.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

All Rights Reserved.