Python:用正则表达式替换所有子字符串事件



我想用正则表达式替换所有子字符串事件。原始句子就像:

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(r"(house|the house)", r"**1**", mystring)

您可以拥有一个未捕获的组,需要注意。如果您查看Regex Patter (?P<repl>(?:the )?house),则(?:the )?部分说,字符串中可能有一个the(如果存在),则将其包括在比赛中。这样,您让re库优化其匹配的方式。这是完整的示例

>>> data = "Carl's house is big. He is asking 1M for that(the house)."
>>> re.sub('(?P<repl>(?:the )?house)', '**g<repl>**', data) 
"Carl's **house** is big. He is asking 1M for that(**the house**)."

注意:g<repl>用于使所有字符串与组<repl>

匹配

您可以进行两次通过:

首先:从最长到最短,替换为:

  • '房屋':'aa_the_house'
  • 'House':'BB_HOUSE'

第二:替换类似:

  • 'aa_the_house':' **the house**'
  • 'bb_house':' **house**'

用一些唯一的值替换字符串,然后用**中的原始字符串替换回来,以使其大胆。

例如:

'the House'带有'temp_the_house'带有" temp_house"的"房子"

然后'temp_house'带' house ''temp_the_house'与'**房屋****'

应该正常工作。您可以使用两个列表来自动化此功能。

最新更新