python - 将内联注释移动到上一行

标签 python regex

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)

See demo on Regex101

关于python - 将内联注释移动到上一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28930477/

相关文章:

python - DRF 不会将原始 JSON 字符串发送到浏览器。它返回一个 JSON 字符串,想要绕过调用 json.load

python - 如何将 "-c"参数正确传递给 pytest.main?

javascript - MAC 地址正则表达式验证逗号分隔、冒号或破折号分隔值

mysql - 在 MySQL 数据库中通过正则表达式选择列的一部分

regex - sbt-scoverage 排除语法

regex - 正则表达式

python - 如何使用 Selenium 和 Python 在 iF​​rame 中定位元素

python - Django/Python 中按查询集计数排序列表

PHP 正则表达式抓取 {tag}something{/tag}

python - 带有真实 "Full Text Search"和拼写错误的 SQLite(FTS+spellfix 一起)