繁体   English   中英

将内联注释移到上一行

[英]Move inline comments to the previous line

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)

请参阅Regex101上的演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM