I asked Gemini 2.5 Flash to just write me a function to do it, and it used regex.
In a separate chat, I asked it to suggest some ways to do it first, and it provided three alternatives, but suggested I started with regex.
FWIW I used Open WebUI, which uses the API (via OpenRouter). I've seen people here mentioning that the API produces much better results than the chat app, for whatever reason.
For reference, here's prompt and the zero-shot result, minus the rigorous comments it added:
I need a Python function that will take in markdown in a string and return a string with ansi codes for bold, italics and underline. Can you write me such a function?
import re
def markdown_to_ansi(markdown_string: str) -> str:
ansi_string = markdown_string
ANSI_BOLD = "\033[1m"
ANSI_ITALIC = "\033[3m"
ANSI_UNDERLINE = "\033[4m"
ANSI_RESET = "\033[0m"
ansi_string = re.sub(r'\*\*(.*?)\*\*', f'{ANSI_BOLD}\\1{ANSI_RESET}', ansi_string)
ansi_string = re.sub(r'__(.*?)__', f'{ANSI_BOLD}\\1{ANSI_RESET}', ansi_string)
ansi_string = re.sub(r'\*(.*?)\*', f'{ANSI_ITALIC}\\1{ANSI_RESET}', ansi_string)
ansi_string = re.sub(r'\_(.*?)\_', f'{ANSI_ITALIC}\\1{ANSI_RESET}', ansi_string)
ansi_string = re.sub(r'\+\+(.*?)\+\+', f'{ANSI_UNDERLINE}\\1{ANSI_RESET}', ansi_string)
# A more robust solution for nesting would require a parsing library or a more complex state machine.
# However, for simple cases, applying in order can layer them correctly.
return ansi_string
Yes, this is a very effective tactic, in my experience! Especially when I am asking for a solution where I am not confident I know what is "best". Having a "pre chat" to settle "what to do" and then "how to do it" before finally telling the LLM to "do it" is often worth the extra time for getting it to provide a solution for complex problems.
In a separate chat, I asked it to suggest some ways to do it first, and it provided three alternatives, but suggested I started with regex.
FWIW I used Open WebUI, which uses the API (via OpenRouter). I've seen people here mentioning that the API produces much better results than the chat app, for whatever reason.
For reference, here's prompt and the zero-shot result, minus the rigorous comments it added:
I need a Python function that will take in markdown in a string and return a string with ansi codes for bold, italics and underline. Can you write me such a function?