from re import compile, MULTILINE, sub
data= """\
# comment1
key1=value1
key2=value2 # comment2
key3=value3 # comment3 #"""
print("----------------------- before sub")
print(data)
print("----------------------- after")
print(sub(compile("^(.*)(#.*)$", MULTILINE), "\\2\\n\\1", data).strip())
你认为可以做得更好(只有一行)吗?
结果
------------------------- before sub
# comment1
key1=value1
key2=value2 # comment2
key3=value3 # comment3 #
------------------------- after
# comment1
key1=value1
# comment2
key2=value2
#
key3=value3 # comment3
我不知道做得更好。
如您所见,只有注释 2 得到了正确处理(行尾空格除外)。
最佳答案
尝试 ^(\s*\S+\s*)(#[^\n]*)
并替换为 \1\n\2
。
print(re.sub(r"^(\s*\S+\s*)(#[^\n]*)", re.MULTILINE), r"\2\n\1", data)
关于python - 将内联注释移动到上一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28930477/