簡體   English   中英

Python:使用正則表達式替換所有出現的子字符串

[英]Python: Replace all substring occurrences with regular expressions

我想用正則表達式替換所有出現的子字符串。 原始句子如下:

mystring = "Carl's house is big. He is asking 1M for that(the house)."

現在,假設我有兩個要加粗的子字符串。 我通過在子字符串的開頭和結尾添加**來加粗單詞。 2個子字符串是:

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)

您可能有一個未被捕獲且需要注意的組。 如果查看正則表達式模式(?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”
  • '房子':'BB_HOUSE'

第二:進行替換,例如:

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

將字符串替換為一些唯一值,然后將其替換為用**括起來的原始字符串,使它們變為粗體。

例如:

'房子'與'temp_the_house''房子'與'temp_house'

然后是“ temp_house”和“ house ”,“ temp_the_house”和“ ** thehouse ****”

應該工作正常。 您可以使用兩個列表來自動執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM