Python 将内联注释移到上一行

Python 将内联注释移到上一行,python,regex,Python,Regex,你认为有可能做得更好吗(只有一行)? 结果 我不知道你能做得更好。 如您所见,只有注释2得到了正确处理(行尾的空格除外)。请尝试^(\s*\s+\s*)(#[^\n]*)并替换为\1\n\2 ------------------------- before sub # comment1 key1=value1 key2=value2 # comment2 key3=value3 # comment3 # ------------------------- after # comment1 k

你认为有可能做得更好吗(只有一行)?
结果

我不知道你能做得更好。
如您所见,只有注释2得到了正确处理(行尾的空格除外)。

请尝试
^(\s*\s+\s*)(#[^\n]*)
并替换为
\1\n\2

------------------------- before sub
 # comment1
key1=value1
key2=value2 # comment2
key3=value3 # comment3 #
------------------------- after
# comment1

key1=value1
# comment2
key2=value2 
#
key3=value3 # comment3

@BhargavRao thanx很多:)我想如果我错过了,我将不得不自己离开豪饮两周,而且这种情况不会再发生了:我记得我刚刚投票决定离开。但是今天我必须在按下“^”按钮之前做一些工作:)很好,很完美,但它必须通过编译,否则它将无法工作。打印(sub(编译(r“^(\s*\s+\s*)(#[^\n]*)”,多行),r“\2\n\1”,数据).strip()。谢谢。
------------------------- before sub
 # comment1
key1=value1
key2=value2 # comment2
key3=value3 # comment3 #
------------------------- after
# comment1

key1=value1
# comment2
key2=value2 
#
key3=value3 # comment3
print(re.sub(r"^(\s*\S+\s*)(#[^\n]*)", re.MULTILINE), r"\2\n\1", data)