|
| 1 | +def remove_code_block_markers(code_string: str, remove_text: bool = True) -> str: |
| 2 | + """Remove code block markers from a markdown code block. |
| 3 | +
|
| 4 | + Parameters |
| 5 | + ---------- |
| 6 | + code_string : str |
| 7 | + The input string containing markdown code block(s) |
| 8 | + remove_text : bool, default=True |
| 9 | + If True, searches for and removes code block markers anywhere in the text. |
| 10 | + If False, only removes markers if they are at the start and end of the text. |
| 11 | +
|
| 12 | + Returns |
| 13 | + ------- |
| 14 | + str |
| 15 | + The code string with code block markers removed. |
| 16 | + If no code block markers are found, returns the original string. |
| 17 | +
|
| 18 | + Notes |
| 19 | + ----- |
| 20 | + Code block markers are identified by the ``` sequence. |
| 21 | + When remove_text=True, this function will find the first and last occurrences |
| 22 | + of code block markers and extract only the code between them. |
| 23 | + When remove_text=False, it only removes the markers if they are at the start |
| 24 | + and end of the string. |
| 25 | + """ |
| 26 | + lines = code_string.strip().split("\n") |
| 27 | + |
| 28 | + if not remove_text: |
| 29 | + # Simple check for code blocks at start and end |
| 30 | + if lines[0].startswith("```") and lines[-1].startswith("```"): |
| 31 | + return "\n".join(lines[1:-1]) |
| 32 | + return code_string |
| 33 | + |
| 34 | + # Find start and end of code block |
| 35 | + start_idx = 0 |
| 36 | + end_idx = len(lines) |
| 37 | + |
| 38 | + for i, line in enumerate(lines): |
| 39 | + if "```" in line: |
| 40 | + start_idx = i + 1 |
| 41 | + break |
| 42 | + |
| 43 | + for i in range(len(lines) - 1, -1, -1): |
| 44 | + if "```" in lines[i]: |
| 45 | + end_idx = i |
| 46 | + break |
| 47 | + |
| 48 | + # If we found a code block, extract just the code |
| 49 | + if start_idx < end_idx: |
| 50 | + return "\n".join(lines[start_idx:end_idx]) |
| 51 | + |
| 52 | + return code_string |
0 commit comments