【问题标题】:remove white space between specific characters using regex in python在python中使用正则表达式删除特定字符之间的空格
【发布时间】:2018-01-02 11:16:03
【问题描述】:

我正在尝试使用正则表达式删除连续“?”序列中的空格和/或“!”在一个字符串中。一个例子是“那是什么?????????!?!”应该改为“那是什么?????????!!!?!”。也就是说,我想连接所有的“?”和 '!'中间没有空格。我当前的代码效果不佳:

import re
s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
s = re.sub("\? +\?", "??", s)
s = re.sub("\? +\!", "?!", s)
s = re.sub("\! +\!", "!!", s)
s = re.sub("\! +\?", "!?", s)

产生'那是什么??? ?????? !?!',其中一些空格显然没有被删除。我的代码出了什么问题以及如何修改它?

【问题讨论】:

    标签: python regex


    【解决方案1】:

    您只是想在标点符号周围压缩空格,是吗?像这样的东西怎么样:

    >>> import re
    >>> s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
    >>> 
    >>> re.sub('\s*([!?])\s*', r'\1', s)
    'what is that??????????!!!?!'
    

    如果您真的对为什么您的方法不起作用感兴趣,它与正则表达式如何在字符串中移动有关。当您编写 re.sub("\? +\?", "??", s) 并在您的字符串上运行它时,引擎会这样运行:

    s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !"
    # first match -----^^^
    # internally, we have:
    s = "what is that ??? ? ?? ??? ? ! ! ! ? !"
    # restart scan here -^
    # next match here ----^^^
    # internally:
    s = "what is that ??? ??? ??? ? ! ! ! ? !"
    # restart scan here ---^
    # next match here ------^^^
    

    等等。有一些方法可以防止光标在检查匹配时前进(查看正向预测)。

    【讨论】:

    • 这是我能找到的最佳解决方案之一。它对我来说还有一个小问题,即对于This is! ? a test! ?,它将返回This is!?a test!?,而我希望有This is!? a test!?(在问号和'a'之间保留空格)。任何进一步的帮助将不胜感激
    【解决方案2】:

    如果你想像@g.d.d.c 所说的那样并且句型相同,那么你可以试试这个:

    string_="what is that ?? ? ? ?? ??? ? ! ! ! ? !"
    string_1=[]
    symbols=[]
    string_1.append(string_[:string_.index('?')])
    symbols.append(string_[string_.index('?'):])
    string_1.append("".join(symbols[0].split()))
    print("".join(string_1))
    

    输出:

    what is that ??????????!!!?!
    

    【讨论】:

      【解决方案3】:

      我的方法是将字符串分成两部分,然后使用正则表达式(删除空格)处理问题区域,然后将这些部分重新组合在一起。

      import re s = "what is that ?? ? ? ?? ??? ? ! ! ! ? !" splitted = s.split('that ') # don't forget to add back in 'that' later splitfirst = splitted[0] s = re.sub("\s+", "", splitted[1]) finalstring = splitfirst+'that '+s print(finalstring) 输出:

      ╭─jc@jc15 ~/.projects/tests ╰─$ python3 string-replace-question-marks.py what is that ??????????!!!?!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        • 2022-08-19
        • 2014-06-26
        • 1970-01-01
        相关资源
        最近更新 更多