简体   繁体   English

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

[英]String replacements using re.sub in python

While learning Python regex, I want to replace all Python 2x like print functions to Python 3x like using re.sub : 在学习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)

Matter of py2.py is: py2.py的问题是:

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

But this code replace print "Anything goes here" to print( , How to capture whole string and replace last quote to ")" a well? 但是这段代码替换了print "Anything goes here"print( ,如何捕获整个字符串并将最后一个引号替换为“)”一个好吗?

You want to use references to the matching groups in your sostitution: 您希望使用对索引中匹配组的引用:

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

Used as: 用作:

>>> import re
>>> matter = """
... print "Anything goes here"
... print "Anything"
... print "Something goes here"
... """
>>> print(re.sub(r'print\s+"(.*)"', r'print("\1")', matter))

print("Anything goes here")
print("Anything")
print("Something goes here")

Note that if your goal is to modify python2 code to be python3 compatible there already exist the 2to3 utility which comes included with python itself. 请注意,如果您的目标是将python2代码修改为python3兼容,那么已经存在python本身附带的2to3实用程序

Try this: 尝试这个:

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

and replace by this: 并由此替换:

 print("\1")

Explanation 说明

You can try this: 你可以试试这个:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM