regex 正则表达式删除块注解,但保留空行?

vuktfyat  于 2022-12-27  发布在  其他
关注(0)|答案(1)|浏览(110)

有没有可能用正则表达式删除块注解而不删除换行符?
假设我有这样一段文字:

text = """Keep this /* this has to go
this should go too but leave empty line */
This stays on line number 3"""

我想出了这个正则表达式:

text = re.sub(r'/\*.*?\*/', '', text, 0, re.DOTALL)

但这给了我:

Keep this 
This stays on line number 3

我想要的是:

Keep this

This stays on line number 3

能做到吗?

o8x7eapl

o8x7eapl1#

我们可以对当前的逻辑做一个小小的修改,使用lambda回调函数代替re.sub

import re

text = """Keep this /* this has to go
this should go too but leave empty line */
This stays on line number 3"""

text = re.sub(r'/\*.*?\*/', lambda m: re.sub(r'[^\n]+', '', m.group()), text, flags=re.S)
print(text)

这将打印:

Keep this 

This stays on line number 3

lambda函数中的替换逻辑作用于/* ... */注解块,它去掉了所有的字符 *,除了换行符的 *,保留了换行符结构,同时删除了中间注解行的所有其他内容。

相关问题