【问题标题】:How to remove specific characters in a string *within specific delimiters*, e.g. within parentheses如何删除字符串中的特定字符*在特定分隔符内*,例如括号内
【发布时间】:2017-05-29 17:44:32
【问题描述】:

在字符串中

my_string = 'abcd (ef gh ) ij'

只有当它们出现在括号内时,我才需要删除空格,结果是:

my_clean_string = 'abcd (efgh) ij'

这个post 建议如何通过re.sub(r'\([^)]*\)', '', my_string) 完全删除所有括号文本,但是我不知道如何指定只应将删除应用于空格' '

是否有一个 regexpr(或简单的 python)解决方案可以在不明确循环每个字符的情况下做到这一点?

【问题讨论】:

    标签: python regex python-2.7 python-3.x


    【解决方案1】:

    下面是一种适用于嵌套括号的通用方法:

    In [27]: my_string = 'abcd (  ()e(e w  )f ) gh'
    
    In [28]: re.sub(r' \(\s+|\s+\)', lambda x: x.group().strip(), my_string)
    Out[28]: 'abcd(()e(e w)f) gh'
    

    如果您想删除单词之间的空格,您可以使用look-arounds ;-):

    In [40]: my_string = 'abcd (  ()e(e w  )f ) gh'
    
    In [41]: re.sub(r'\s+(?=[^[\(]*\))|((?<=\()\s+)', '', my_string)
    Out[41]: 'abcd (()e(ew)f) gh'
    

    【讨论】:

    • 你能去掉括号内单词之间的空格吗?
    • @Kasramvd split and join 也适用于您的嵌套正则表达式。更新它。
    【解决方案2】:

    这将删除括号内单词前后的空格。

    import re
    my_string = 'abcd (   ef dfg dfg  ) gh'
    print re.sub('\(\s*(.*?)\s*\)', lambda x: ''.join(x.group().split()), my_string, re.DOTALL)
    

    输出:

    abcd (efdfgdfg) gh
    

    【讨论】:

    • 我需要删除所有空格,包括在单词之间,例如abcd (efdfgdfg) gh 在你的情况下
    • @Pythonic 已更新。
    • @Pythonic 考虑换行,你可以使用re.DOTALL
    【解决方案3】:

    不使用正则表达式的解决方案,

    my_string = 'abcd (ef ) gh'
    str_to_replace = my_string[my_string.find('(')+1:my_string.find(')')]
    out = my_string.replace(str_to_replace,str_to_replace.replace(' ',''))
    

    结果

    abcd (ef) gh

    【讨论】:

      【解决方案4】:

      与此post有关,

      re.sub("\\s+(?=[^()]*\\))", "", my_string)
      

      【讨论】:

      • 这不适用于'abcd ( ()e(e w )f ) gh'等字符串
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-19
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      相关资源
      最近更新 更多