python - 在 python 中使用 re.sub 进行字符串替换

标签 python regex

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

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(, How to capture whole string and replace last quote to ")"a well?

最佳答案

您想在您的搜索中使用对匹配组的引用:

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

用作:

>>> 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")

请注意,如果您的目标是将 python2 代码修改为与 python3 兼容,则 2to3 utility 已经存在它包含在 python 本身中。

关于python - 在 python 中使用 re.sub 进行字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40380567/

相关文章:

python - 以表格格式打印嵌套字典键和值

python - "Global name not defined"错误

java - 多行模式的正则表达式可选匹配

java - 匹配正则表达式组以在 java 中列出(赫斯特模式)

java - 理解字符串模式的问题

python - 在 python re 中分隔字符串中的第一个单词

需要 Javascript 正则表达式帮助

python - 从 CSV 文件行中的值确定数据类型

python - 无法更新 CharField - Django

python - 如何将 C++ python 扩展导入到另一个目录中的模块中?