regex (vim) for print ... to print(...) for python2 to python3 [英] regex (vim) for print ... to print(...) for python2 to python3

查看:40
本文介绍了regex (vim) for print ... to print(...) for python2 to python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

帖子仅当您在其中包含字符串时才有帮助打印命令.现在我有大量带有声明的源代码,例如

This post is helpful only if you have strings inside of the print command. Now I have tons of sourcecode with a statement such as

print milk,butter

应该格式化为

print(milk,butter)

并且用 \n 捕获行尾没有成功.有什么提示吗?

And capturing the end of the line with \n was not sucessfull. Any hints?

推荐答案

我对 2to3 不熟悉,但从所有评论来看,它看起来是适合这项工作的正确工具.

I am not familiar with 2to3, but from all the comments, it looks like the correct tool for the job.

也就是说,也许我们可以用这个问题作为一些 vim 基础知识的简短课程的借口.

That said, perhaps we can use this question as an excuse for a short lesson in some vim basics.

首先,您需要一个匹配正确行的模式.我认为 ^\s*print\> 会做:

First, you want a pattern that matches the correct lines. I think that ^\s*print\> will do:

  • ^ 匹配行首(而 $ 匹配行尾).
  • \s 匹配空白(空格或制表符)
  • * 表示前一个原子的 0 个或多个(尽可能多,或贪婪").
  • print 是一个文字字符串.
  • \> 匹配词尾(零宽度).您可以使用(文字)空格或 \s\+ 代替.
  • ^ matches start of line (and $ matches end of line).
  • \s matches whitespace (space or tab)
  • * means 0 or more of the previous atom (as many as possible, or "greedy").
  • print is a literal string.
  • \> matches end-of-word (zero width). You might use a (literal) space or \s\+ instead.

接下来,您需要确定要括在括号中的部分.由于 * 是贪婪的,.* 将匹配到行尾;无需将其锚定在右侧.使用 \(\s*print\)\(.*\) 捕获片段,以便您可以将它们称为 \1\2 在替换中.

Next, you need to identify the part to be enclosed in parentheses. Since * is greedy, .* will match to the end of the line; there is no need to anchor it on the right. Use \(\s*print\) and \(.*\) to capture the pieces, so that you can refer to them as \1 and \2 in the replacement.

现在,将各个部分放在一起.有很多变种,我还没有尝试打高尔夫球"这个:

Now, put the pieces together. There are many variants, and I have not tried to "golf" this one:

:%s/^\(\s*print\)\s\+\(.*\)/\1(\2)

有些人更喜欢非常神奇"的版本,其中只有 a-z、A-Z、0-9 和 _ 被视为文字字符;那么你不需要转义括号或加号:

Some people prefer the "very magic" version, where only a-z, A-Z, 0-9, and _ are treated as literal characters; then you do not need to escape the parentheses nor the plus:

:%s/^\v(\s*print)\s+(.*)/\1(\2)

这篇关于regex (vim) for print ... to print(...) for python2 to python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆