如何在Python中删除单词之间的多个空格,而没有前导空格

问题描述 投票:1回答:2

我正在编写一个简单的Sublime Text插件,以修剪单词之间多余的,不必要的空格,但又不要触碰前导空格以免弄乱Python的格式。

我有:

[spaces*******are********here]if****not***regions***and**default_to_all:

并且想要得到:

[spaces***are***still****here]if not regions and default_to_all:

思考

regions = view.find_all('\w\s{2,}\w')
view.erase(edit, region)

但它也删去了第一个和最后一个字母。

python sublimetext sublime-text-plugin
2个回答
1
投票

对于不匹配的前导空格表示您要匹配非空格字符后的一堆空格(并用单个空格替换)

因此您可以将(?<=\S) +(?=\S)替换为单个空格

说明:

(?<=\S) +(?=\S)
(?<=              Positive look-behind, which means preceded by...
    \S                non-space character
      )           end of look-behind group
        +         more than 1 space
         (?=\S)   Positive look-ahead, which means followed by...
                      non-space character
                  end of look-ahead group

应该直接理解。不过,您可能需要稍微调整一下以处理空间。

https://regex101.com/r/WpvWl3/2

但是,关于您的意图,请注意:这将不是重新格式化代码的可靠方法。除了前导空格外,仍有许多重要的多重空格情况。最明显的一个是字符串文字中的空格。


1
投票

如果我理解正确,那应该可以:

>>> r = re.compile(r'( *[\S]*)(?: +)(\n)?')
>>> s = '       if   not regions    and  default_to_all:\n     foo'
>>> r.sub(' ', s)
   if not regions and default_to_all:
 foo
© www.soinside.com 2019 - 2024. All rights reserved.