regexp替换直到评论

时间:2012-04-17 21:32:33

标签: python regex replace

我有这个文件:

 # blah blah blah DO NOT REPLACE blah blah
 blah blah blah
 blah blah REPLACE # comment comment
 REPLACE blah blah

注释以“#”开头,​​我想替换不在注释中的关键字。

我正在使用python,我该怎么做?

2 个答案:

答案 0 :(得分:3)

不要使用正则表达式。相反,将行拆分为#字符,只使用第一部分:

>>> lines = '''
...  # blah blah blah DO NOT REPLACE blah blah
...  blah blah blah
...  blah blah REPLACE # comment comment
...  REPLACE blah blah
... '''
>>> [l.split('#', 1) for l in lines.split('\n')]
[[''], 
 [' ', ' blah blah blah DO NOT REPLACE blah blah'], 
 [' blah blah blah'], 
 [' blah blah REPLACE ', ' comment comment'], 
 [' REPLACE blah blah'], ['']]

您现在可以编写代码(可能使用其他列表解析)来替换第一部分中REPLACE的出现并重新加入整个事物。

答案 1 :(得分:0)

我同意Niklas B,你不需要正则表达式来解决你的问题。

您可以使用以下内容:

>>> f = lambda text, sub, repl: \
... '\n'.join([line.split('#')[0].replace(sub, repl) + '#' + line.split('#',1)[1] \
... if '#' in line else line.replace(sub, repl)
... for line in text.split('\n')])

然后,如果你有

>>> text = """# blah blah blah DO NOT REPLACE blah blah
...  blah blah blah
...  blah blah REPLACE # comment comment
...  REPLACE blah blah"""

并想要为'%%%%'替换“REPLACE”,你可以使用函数f:

>>> print f(text, 'REPLACE', '%%%%')
# blah blah blah DO NOT REPLACE blah blah
 blah blah blah
 blah blah %%%% # comment comment
 %%%% blah blah