代码之家  ›  专栏  ›  技术社区  ›  MetallicPriest

如何用修改过的匹配字符串替换正则表达式中的匹配字符串

  •  -1
  • MetallicPriest  · 技术社区  · 7 年前

    让我们举个例子 here .

    #!/usr/bin/python
    import re
    
    phone = "2004-959-559 # This is Phone Number"
    
    # Delete Python-style comments
    num = re.sub(r'#.*$', "", phone)
    print "Phone Num : ", num
    

    这里,让我们说,我只想用修改过的匹配文本替换那些注释,而不是删除注释。例如,用C样式的注释替换python样式的注释,这样 # This is Phone Number 变成 /* This is a Phone Number */ . 我该怎么做?

    2 回复  |  直到 7 年前
        1
  •  4
  •   anubhava    7 年前

    您可以在替换字符串中使用捕获组和后引用:

    >>> phone = "2004-959-559 # This is Phone Number"
    >>> print re.sub(r'#(.*)$', r'/* \1 */', phone)
    2004-959-559 /*  This is Phone Number */
    
    • (.*) 在之后捕获字符串 # 在第一个捕获组中。
    • \1 是匹配regex中第一个捕获组的后引用 re.sub .
    • 必须使用原始字符串模式替换才能解释 1 适当地。
        2
  •  0
  •   RedKoder    7 年前

    根据您的注释示例,str.replace应该适用于您:

    >>>
    >>> str1 = "# This is a Phone Number"
    >>> str2 = str1.replace("#", "/*") + " */"
    >>>
    >>> str2
    '/* This is a Phone Number */'
    >>>