簡體   English   中英

如何不使用REGEX刪除具有特定模式的字符串?

[英]How to remove a string with specific pattern without using REGEX?

這些輸入和輸出集讓我很難過:

input: so sh [/] she had a [^ wheee] .
output: so sh [/] she had a .

input: aah [!] [^ makes sound effects] .
output: aah.

input: and she say (.) I got it [^ repeats 2 times] .
output: and she say (.) I got it .

input: oh no[x 3] .
output: oh  no.


input: xxx [^ /bosolasafiso/]
output: xxx

input: hi [* med]
oupt: hi [* med]

我使用了REGEX,但沒有用,我需要精確的條件來使所有這些條件都滿足,並且應該返回結果輸出。

正在從文件中讀取所有“輸入”,因此請注意,即使我使用“ split()”,諸如[^ whee]之類的單詞也將被視為兩個不同的單詞。

我需要一個條件,其中僅保留包含[/] [*單詞。 以“ [”開頭的其他單詞應替換為空字符串。

假定原始文本中沒有大括號,則以下解決方案有效。 否則,請使用其他一對定界符(例如<<>> )。

s1 = 'so sh [/] [* med] she had a [^ wheee] .' 

首先,代替[]在每個[/ X][* X]與片段{} ,分別以保護它們免受消除。 然后在方括號中消除所有監視的片段。 最后,將所有花括號放回方括號中:

re.sub(r"\[[^]]*]", "", # Remove [Y] blocks
        re.sub(r"\[([/*][^]]*)]", r"{\1}", s1)) # Rename [X] to {X}\
  .replace("{", "[") # Restore the original brackets\
  .replace("}", "]")
#'so sh [/] [* med] she had a  .'

暫無
暫無

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

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