【发布时间】:2023-03-21 23:20:02
【问题描述】:
我正在尝试使用正则表达式将字符串中的 * 替换为 <em> 或 </em> 标记。
例如:
My *name* is John 输出My <em>name</em> is John
但是,如果相邻有**,我不想用<em> 替换它们。
我有以下代码。问题是当我运行它时,它会将** 替换为<em> 和</em>。我想要
Hello *there* are two aster**es next to each other
输出
Hello <em>there</em> are two aster**es next to each other
我得到了
Hello <em>there</em> are two aster<em></em>es next to each other
我的代码:
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)
我的测试:
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)
测试失败,我得到:
Hello <em>there</em> are two aster<em></em>es es next to each other
【问题讨论】:
-
*Hel lo * there* ar**e two *ast***er*es ne*xt to **each ot**her***********的输出应该是什么?