【发布时间】:2016-07-28 19:30:58
【问题描述】:
我有一个类似的字符串:The old man $went$ to the $barn$. 我如何将其转换为The old man ~!went! to the ~!barn!.
如果我不需要在第一次出现的前面添加~,我可以在 Python 中简单地执行text.replace('$', '!')。
【问题讨论】:
-
re.sub(r'\$(\w+)\$', r'~!\1!', s) -
或者另一个只匹配在单词边界内的美元:
re.sub(r'\$\b([^$]+)\b\$', r'~!\1!', s)。它们中的任何一个或以下任何答案对您有用吗?