[英]How to remove multiple spaces between words in Python, without the leading spaces
I'm writing a simple Sublime Text plugin to trim extra, unnecessary, spaces between words but without touching the leading spaces not to mess up Python formatting.我正在编写一个简单的 Sublime Text 插件来修剪单词之间多余的、不必要的空格,但不触及前导空格,以免弄乱 Python 格式。
I have:我有:
[spaces*******are********here]if****not***regions***and**default_to_all:
and want to get:并想得到:
[spaces***are***still****here]if not regions and default_to_all:
Thinking about想着
regions = view.find_all('\w\s{2,}\w')
view.erase(edit, region)
but it cuts out the first and the last letter too.但它也删掉了第一个和最后一个字母。
If I understand correctly, this should work:如果我理解正确,这应该有效:
>>> 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
For non-matching leading spaces implies you want to match multiple spaces following a non-space character (and replace it with single space), so you can replace (?<=\\S) +(?=\\S)
with single space "对于不匹配的前导空格意味着您要匹配非空格字符后面的多个空格(并将其替换为单个空格),因此您可以将
(?<=\\S) +(?=\\S)
替换为单个空格“ ".
”。
Explanation:解释:
(?<=\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
That should be straight-forward to understand.这应该很容易理解。 You may need to tweak it a bit for trailing space handling though.
不过,您可能需要稍微调整一下以进行尾随空间处理。
See " regular expressions 101 " for more information.有关更多信息,请参阅“正则表达式 101 ”。
However, just as a side note regarding your intention: This is not going to be a reliable way to reformat code.但是,就像关于您的意图的旁注:这不是重新格式化代码的可靠方法。 Apart from leading spaces, there are still many cases of multiple-spaces that are significant.
除了前导空格之外,还有很多多空格的情况很重要。 The most obvious one is spaces within string literal.
最明显的是字符串文字中的空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.