【问题标题】:Remove text between two certain characters (multiple occurrences)删除两个特定字符之间的文本
【发布时间】: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 来执行此操作。

标签: python regex


【解决方案1】:

只有一个序列可以删除这个作品:

import re
str = "hi.-hello
 good morning"
re.sub(r"-.*?
", "", str)

【讨论】:

    【解决方案2】:

    这是我的解决方案,

    s = "hi.-hello
     good morning"
    s_clear = s.split("-", 1)[0]+s.split("
    ", 1)[-1]
    
    'hi. good morning'
    

    【讨论】:

    • 如果字符串有多个匹配项,如 hi.-hello good morning -abc ,则不起作用
    猜你喜欢
    • 1970-01-01
    • 2019-01-24
    • 2017-10-24
    • 2014-04-26
    • 1970-01-01
    • 2014-09-01
    • 2015-11-10
    • 1970-01-01
    • 2017-12-04
    相关资源
    最近更新 更多