在 jupyter 笔记本中使用匹配替换查找和替换实用程序

Use match in replace of find and replace utility in jupyter notebook

我想在我的 jupyter notebook 中替换打印功能 带有包装函数。

我可以将打印语句与 javascript 正则表达式 print\(.*\) 匹配,但从那里我不确定如何在替换文本字段中再次使用匹配:

def verb_printer(msg, verb):
    if verb:
        print(msg)

我尝试了 verb_printer() 之类的方法来访问匹配项,但没有成功。

如何解决这个问题?

你原来的表达式很好,我们只添加一个捕获组(),这样当我们将它替换为verb_printer()时,我们想要的字符串已经被捕获:

(print\(.*\))

Demo

测试

const regex = /(print\(.*\))/gm;
const str = `def verb_printer(msg, verb):
    if verb:
        print(msg)
`;
const subst = `verb_printer()`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log(result);