I am trying to use regex to replace the * in a string with an <em> or </em> tag.
For example:
My *name* is John outputs My <em>name</em> is John
However, if there are ** next to each other, I don't want to replace them with <em>.
I have the following code. The problem is that when I run it, it replaces the ** with <em> and </em>. I want
Hello *there* are two aster**es next to each other
to output
Hello <em>there</em> are two aster**es next to each other
Instead I get
Hello <em>there</em> are two aster<em></em>es next to each other
My code:
def emphasis(string):
regex = re.compile('(\s?)\*(.*?)\*(\s?)')
return re.sub(regex, replace_function, string)
def replace_function(input):
match = input.group()
if match:
return re.sub('(\s?)\*(.*?)\*(\s?)', '\\1<em>\\2</em>\\3', match)
My test:
def test_if_two_asterix_are_next_to_each_other(self):
title = "Hello *there* are two aster**es next to each other"
expected = "Hello <em>there</em> are two aster**es next to each other"
actual = _emphasis(title)
self.assertEqual(actual,expected)
The test fails and instead I get:
Hello <em>there</em> are two aster<em></em>es es next to each other