【问题标题】:regexp replace until comment正则表达式替换直到评论
【发布时间】:2012-04-17 21:32:32
【问题描述】:

我有这个文件:

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

cmets 以“#”开头,我想替换注释中没有的关键字。

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

【问题讨论】:

  • 你的代码在哪里?
  • str="Boy, am I ever glad that I can use '#' in strings!"

标签: python regex replace


【解决方案1】:

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

>>> 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 并重新加入整个内容。

【讨论】:

    【解决方案2】:

    我同意 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 2022-01-01
      • 1970-01-01
      • 2015-04-09
      相关资源
      最近更新 更多