[英]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())
Do you think it is possible to do better (only one line)? 你认为有可能做得更好(只有一行)吗?
Result 结果
------------------------- before sub
# comment1
key1=value1
key2=value2 # comment2
key3=value3 # comment3 #
------------------------- after
# comment1
key1=value1
# comment2
key2=value2
#
key3=value3 # comment3
I do not know do better. 我不知道做得更好。
As you see, only the comment 2 is properly treated (except space at end of line).
如您所见, 只有评论2被正确处理 (除了行尾的空格)。
Try ^(\\s*\\S+\\s*)(#[^\\n]*)
and replace by \\1\\n\\2
. 尝试
^(\\s*\\S+\\s*)(#[^\\n]*)
并替换为\\1\\n\\2
。
print(re.sub(r"^(\s*\S+\s*)(#[^\n]*)", re.MULTILINE), r"\2\n\1", data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.