簡體   English   中英

Python 正則表達式刪除某些模式之間的文本

[英]Python regex to remove text between some pattern

我有以下格式的文本。

|開始| 這是第一個要刪除的段落|end| .
這是另一個文本。
|開始| 這是另一個要刪除的段落|end| . 又是一些自由文本

我想刪除 |start| 之間的所有文本和 |結束|

我已經嘗試過關注。

regex = '(?<=\|start\|).+(?=\|end\|)'
re.sub(regex, ''. text)

它返回

“又是一些自由文本”

但我希望回來

這是另一個文本。 又是一些自由文本

請注意,開始/結束分隔符位於模式中的環視結構中,因此將保留在re.sub之后的結果字符串中。 您應該將lookbehind 和lookahead 轉換為消費模式。

此外,您似乎想刪除右手定界符后的特殊字符,因此您需要在正則表達式的末尾添加[^\w\s]*

您可以使用

import re
text = """|start| this is first para to remove |end|.
this is another text.
|start| this is another para to remove |end|. Again some free text"""
print( re.sub(r'(?s)\|start\|.*?\|end\|[^\w\s]*', '', text).replace('\n', '') )
# => this is another text. Again some free text

請參閱Python 演示

正則表達式詳細信息

  • (?s) - 內聯 DOTALL 修飾符
  • \|start\| - |start| 文本
  • .*? - 任何 0+ 個字符,盡可能少
  • \|end\| - |end| 文本
  • [^\w\s]* - 除了單詞和空格字符之外的 0 個或多個字符。

嘗試這個:

import re

your_string = """|start| this is first para to remove |end|.
this is another text.
|start| this is another para to remove |end|. Again some free text"""

regex = r'(\|start\|).+(\|end\|\.)'

result = re.sub(regex, '', your_string).replace('\n', '')

print(result)

輸出:

this is another text. Again some free text

暫無
暫無

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

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