【发布时间】:2022-11-25 21:16:24
【问题描述】:
我想删除字符“-”和字符串“\n”中的文本 (人物也一样)
例如,string = "hi.-hello\and good morning" 我想要得到的结果是 string = "hi. good morning"
我找到了这些示例(作为如何调整我想要的示例的参考)
import re
str = "hi.)hello| good morning"
re.sub(r"(?<=\)).*?(?=\|)", "", str)
>>>'hi.)| good morning'
还有这个
>>> import re
>>> x = "This is a sentence. (once a day) [twice a day]"
>>> re.sub("([\(\[]).*?([\)\]])", "\g<1>\g<2>", x)
'This is a sentence. () []'
和这个
>>> import re
>>> x = "This is a sentence. (once a day) [twice a day]"
>>> re.sub("[\(\[].*?[\)\]]", "", x)
'This is a sentence. '
但我仍然无法获得我的案例的语法。我也想学习它的一般语法(即定制)。
【问题讨论】:
-
re.sub(r"-.*\n", "", string)适合你吗? -
您不必使用正则表达式。您可以简单地使用
replace来执行此操作。