我正在使用notepad++重新格式化Python脚本,但有些行没有缩进4(或8、12、16等)。空格。
因此,我需要匹配连续的前导空格(即每行开头的缩进),这些空格不是4的倍数,即1、2、3、5、6、7、9、10、11等的空格。
例如:
>>> a = 1 # match this, as there're 3 spaces at the beginning
>>> b = a # match this too, as indent by 7 spaces
>>> c = 2 # but not this, since it's indented exactly by 4 spaces
>>> d = c # not this either, since indented by 8 spaces我能够在4的倍数中匹配空格,使用如下所示:
^( {16}| {12}| {8}| {4})然后我试着用这样的东西来匹配相反的东西:
^[^( {16}| {12}| {8}| {4})]但它只匹配空行或行开头的字符,而不是我想要的。
我是个十足的新手,但我找了好几个小时却没有运气。我知道我总能与列出的所有非多重数字相匹配,但我希望有人能帮忙,并提供一个不那么麻烦的方法。
谢谢。
更新1
使用regex (@ using 2864740)
^(?:\s{4})*\s{1,3}\S或(@alpha bravo)
^(?!(\s{4})+\S)(.*)匹配非多重的4个缩进,以及空行与4 (8,16等)。空格和它们后面的第一个非空行的第一个字符。
例如: (在regex101.com上)
如何避免匹配上述示例中描述的这些情况?
发布于 2014-08-15 02:38:30
字符类只能包含..。一组字符,因此[^..]不适合一般否定。正则表达式[^( {16}| {12}| {8}| {4})]等价于[^( {16}|284],它将匹配未列出的每个字符。
现在,如果不匹配4个空格的倍数,就等于查找n mod 4 = {1, 2, 3} (或除n mod 4 = 0以外的任何东西)空间。这可以通过如下模式来完成:
(?:\s{4})*\s{1,3}\S解释:
(?:\s{4})* - match any number of whole groups of 4 spaces and then ..
\s{1,3} - match any count of 1, 2, or 3 spaces such that ..
\S - they are not followed by a space正则表达式可能需要一个尾随点(.*)或前导线锚(^),这取决于它的使用方式。
发布于 2014-08-15 02:43:34
我可以提供一个python脚本,它可以告诉您哪些行缩进不当:
with open('path/to/code/file') as infile:
for i,line in enumerate(infile,1):
total = len(line)
whitespace = total-len(line.lstrip(' '))
if whitespace%4:
print("Inconsistent indenting on line", i)发布于 2014-08-15 05:24:06
您可以使用此模式^(?!(\s{4})+\S)(.*) 演示
https://stackoverflow.com/questions/25320471
复制相似问题