首页 > 解决方案 > 如何在不使用 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] 这样的词也会被视为两个不同的词。

[/] [*我需要一个条件,只保留包含的单词 。其他以“[”开头的单词应替换为空字符串。

标签: pythonstringfile

解决方案


以下解决方案有效,假设您的原始文本中没有大括号。否则,请使用其他一些分隔符对(例如,<<>>)。

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

首先,将每个or片段中的and分别替换为 和 ,以防止它们被消除[。然后消除方括号中的所有幸存片段。最后,将所有花括号替换回方括号:][/ 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  .'

推荐阅读