【发布时间】:2016-02-26 16:12:43
【问题描述】:
我尝试使用标志 re.MULTILINE。
我阅读了这些帖子:Bug in Python Regex? (re.sub with re.MULTILINE)、Python re.sub MULTILINE caret match,但它不起作用。 代码:
import re
if __name__ == '__main__':
txt = "\n\
<?php\n\
/* Multi-line\n\
comment */\n\
$var = 1;\n"
new_txt = re.sub(r'\/\*[.\n]*?\*\/', '', txt, flags=re.MULTILINE)
print("\n=========== TXT ============")
print(txt)
print("\n=========== NEW TXT ============")
print(new_txt)
代码输出:
=========== TXT ============
<?php
/* Multi-line
comment */
$var = 1;
=========== NEW TXT ============
<?php
/* Multi-line
comment */
$var = 1;
但new_txt不应包含多行注释。 我想获得没有多行注释的 txt。你有什么想法吗?
【问题讨论】:
-
你需要使用
re.S标志而不是re.M,并将点放在字符类之外。 -
基本上您希望
[.\n]匹配除*/之外的任何内容,对吗?为什么不使用[^\*\/]+?这将使\/\*[^\*]*\*\/匹配您的多行注释而没有标志。