使用python中的re.sub替换字符串

时间:2016-11-02 12:58:38

标签: python regex

在学习Python正则表达式时,我想像使用re.sub一样将所有Python 2x像打印函数替换为Python 3x:

import re

with open("py2.py", "r") as f:
    matter = f.read()
mtr = re.sub(r"print\s+\"(.+)\"+",r"print(", matter)
with open("pr.py", "w") as f:
    final = f.write(mtr)

py2.py的问题是:

print "Anything goes here"
print "Anything" 
print "Something goes here" 

但是这段代码将print "Anything goes here"替换为print(,如何捕获整个字符串并将最后一个引号替换为“)”井?

2 个答案:

答案 0 :(得分:2)

您希望使用对索赔中匹配组的引用:

#import "DateTools/NSDate+DateTools.h"

用作:

re.sub(r'print\s+"(.*)"', r'print("\1")', matter)

请注意,如果您的目标是将python2代码修改为python3兼容,那么已经存在python本身附带的2to3 utility

答案 1 :(得分:1)

试试这个:

print\s+\"(.+)\"

并替换为:

 print("\1")

Explanation

你可以试试这个:

import re

regex = r"print\s+\"(.+)\""

test_str = ("print \"Anything goes here\"\n"
    "print \"Anything\" \n"
    "print \"Something goes here\" ")

subst = " print(\"\\1\")"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)