【问题标题】:Python: Replace all substring occurrences with regular expressionsPython:用正则表达式替换所有出现的子字符串
【发布时间】: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


【解决方案1】:

您可以一次搜索所有字符串,因此一个是另一个的子字符串这一事实并不重要:

re.sub(r"(house|the house)", r"**\1**", mystring)

【讨论】:

  • \1 是什么意思? | 是什么意思?
  • @wwii \1 指的是第一个匹配的组,| 是一个or 运算符,它可以帮助您拥有house or the house 的模式
【解决方案2】:

您可能有一个未捕获且需要注释的组。如果您查看正则表达式模式(?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&lt;repl&gt;用于获取组&lt;repl&gt;匹配的所有字符串

【讨论】:

    【解决方案3】:

    你可以做两遍:

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

    • “房子”:“AA_THE_HOUSE”
    • “房子”:“BB_HOUSE”

    第二:通过替换喜欢:

    • 'AA_THE_HOUSE':'**the house**'
    • 'BB_HOUSE': '**house**'

    【讨论】:

      【解决方案4】:

      用一些唯一值替换字符串,然后用**括起来的原始字符串替换它们以使其变为粗体。

      例如:

      带有“temp_the_house”的“房子” 'house' 与 'temp_house'

      然后是 'temp_house' 和 'house' 'temp_the_house' 与 '**the house****'

      应该可以正常工作。您可以使用两个列表自动执行此操作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-25
        • 1970-01-01
        • 2022-11-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多