繁体   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