Python中文
首页
教程
问答
标签
搜索
登录
注册
Python正则表达式问题:剥离多行注释,但维护一行b
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>我正在分析一个源代码文件,我想删除所有行注释(即以“/”开头)和多行注释(即/<e m>。。。。</em>/)。但是,如果多行注释中至少有一个换行符(\n),则我希望输出只有一个换行符。</p> <p>例如,代码:</p> <pre><code>qwe /* 123 456 789 */ asd </code></pre> <p>应该变成:</p> <pre><code>qwe asd </code></pre> <p>而不是“qweasd”或:</p> <pre><code>qwe asd </code></pre> <p>最好的方法是什么? 谢谢</p> <hr/> <p>编辑: 测试示例代码:</p> <pre><code>comments_test = "hello // comment\n"+\ "line 2 /* a comment */\n"+\ "line 3 /* a comment*/ /*comment*/\n"+\ "line 4 /* a comment\n"+\ "continuation of a comment*/ line 5\n"+\ "/* comment */line 6\n"+\ "line 7 /*********\n"+\ "********************\n"+\ "**************/\n"+\ "line ?? /*********\n"+\ "********************\n"+\ "********************\n"+\ "********************\n"+\ "********************\n"+\ "**************/\n"+\ "line ??" </code></pre> <p>预期结果:</p> <pre><code>hello line 2 line 3 line 4 line 5 line 6 line 7 line ?? line ?? </code></pre>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>这就是你要找的吗?</p> <pre><code>>>> print(s) qwe /* 123 456 789 */ asd >>> print(re.sub(r'\s*/\*.*\n.*\*/\s*', '\n', s, flags=re.S)) qwe asd </code></pre> <p>这只适用于那些不止一行的评论,而不会影响其他评论。</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
Python猜字gam
4 回答
Python猜字游戏
2 回答
Python猜字游戏?
1 回答
Python猜字游戏不会在玩家猜测所有字母时结束
3 回答
Python猜字游戏在有重复字符的单词上失败
7 回答
Python猜想
9 回答
Python猜数字游戏,而循环没有响应
9 回答
python猜测gam的代码反馈
2 回答
python猜测gam的变量问题
10 回答
python猜测具体路径?
8 回答
Python猜测我的号码(反向号码猜测)UnboundLocalE
5 回答
python猜测该数字在猜测过度后再试一次
7 回答
Python猜猜单词游戏bug
1 回答
Python猜猜游戏如何再现
1 回答
Python猜猜游戏服务器
1 回答
Python猜猜谁的游戏我没有得到我预期的输出
8 回答
Python猜谜游戏
3 回答
Python猜谜游戏,值错误:randrange()的空范围
3 回答
Python猜谜游戏,带尝试选项
9 回答
Python猜谜游戏,我的赢的条件打印赢和输
3 回答