Anki Addon Programming - Regex to get the answers to the cloze cards

Note: I found this blog posts somewhere in my notes. Since I did not note, when did I write it, I posted it with the today's date.

Usually, when I am searching for cloze answers in my cards, I was using the following regex.

regex = r"{{c\d+::(.+?)::.+?}}"

answers = re.findall(regex, note.fields)

And for my cases, it even worked alright, since only my language note have cloze cards and all of them have a hint. Since I am mostly using them for reading cards and recognition.

But as I was thinking, if there is a more general way to do it. Since not everybody will have only cloze cards with hints. And here is the solution to this.

regex = r"{{c\d+::(.+?)}}"


answers = [answer.split("::")[0] for answer in re.findall(regex, note.fields)]

This works, since if there is only one double column in the cloze, then the cloze does not have a hint, and the entire thing is an answer. Splitting does not do anything, since it only provides the list with answer as the element, which we then use. But if there is more than one, then splitting on the double column causes the answer and hint to split, and only the answer is taken out.