【发布时间】:2016-12-13 21:00:56
【问题描述】:
我想用正则表达式替换所有出现的子字符串。原来的句子是这样的:
mystring = "Carl's house is big. He is asking 1M for that(the house)."
现在假设我有两个要加粗的子字符串。我通过在子字符串的开头和结尾添加 ** 来加粗单词。两个子字符串是:
substring1 = "house", so bolded it would be "**house**"
substring2 = "the house", so bolded it would be "**the house**"
最后我想要的原句是这样的:
mystring = "Carl's **house** is big. He is asking 1M for that(**the house**)."
主要问题是因为我有几个要替换的子字符串,它们可以像上面的例子一样重叠单词。如果我首先分析最长的子字符串,我会得到:
Carl's **house** is big. He is asking 1M for that(**the **house****).
另一方面,如果我先分析最短的子串,我会得到:
Carl's **house** is big. He is asking 1M for that(the **house**).
似乎我需要从最长的子字符串替换为最短的子字符串,但我想知道我应该如何在第一次替换但在第二次替换时考虑它。还要记住子字符串可以在字符串中出现多次。
注意://假设字符串**永远不会出现在原始字符串中,所以我们可以用它来加粗我们的单词
【问题讨论】:
-
re.sub()可以为 repl 参数提供一个函数。创建一个匹配您的子字符串的模式,然后创建一个函数,该函数将匹配对象作为参数并返回您想要修改的字符串。
标签: python regex string python-2.7 replace