简体   繁体   English

如何在vim中查找和替换这样的东西?

[英]How to find and replace something like this in vim?

Input输入

if(statement)
{

to Ouput到输出

if ( statement ) {

I can find the input using我可以找到输入使用

/if(\S\(.*\))

Explanation :解释 :

if( is the keyword to be searched , \\S to negate whitespace , (.*) for anything in between and ) end bracket. if( 是要搜索的关键字, \\S 否定空格, (.*) 和 ) 结束括号之间的任何内容。

Need :需要 :

Trying to automate coding guideline over code written w/o coding guideline plus I am a lazy coder who wants to run autocmd for coding guidelines.试图在没有编码指南的情况下编写代码自动化编码指南加上我是一个懒惰的编码器,他想运行 autocmd 来获取编码指南。

EDIT :编辑 :

:%s/if(\S\(.*\)\S)/if ( \1 )/gc

Came very close but it removes the first character after the 'if(' and last char before ')'非常接近,但它删除了 'if(' 之后的第一个字符和 ')' 之前的最后一个字符

:%s/if(\(\S.*\S\))/if ( \1 )/gc

\\1 here is for replacing the first match pattern that is between ( ) so in my case it was \\S.*\\S \\1 这里用于替换 ( ) 之间的第一个匹配模式,所以在我的情况下它是 \\S.*\\S

\\S.*\\S is for anything without any whitespace. \\S.*\\S 用于没有任何空格的任何内容。

There's no need for :substitute here;这里不需要:substitute ; you already have the regular expression, you can use that with :global to find all lines and then :join them with the next one:您已经有了正则表达式,您可以将其与:global一起使用来查找所有行,然后:join它们与下一行:

:global /if(\S\(.*\))/join

If you prefer :substitute , you can do that as well, by matching the newline ( \\n ), any indent, and the opening curly.如果您更喜欢:substitute ,您也可以通过匹配换行符 ( \\n )、任何缩进和开头卷曲来做到这一点。 I use \\zs here to limit the match;我在这里使用\\zs来限制匹配; this saves me from using capturing groups :这使我免于使用捕获组

:%substitute/if(\S\(.*\)\zs\n\s*{/ {/

Attention!注意力! Caveats注意事项

You say your intention is automation of coding guidelines.你说你的意图是编码指南的自动化。 While Vim commands such as the above are fine for occasional tactical edits, I would not base an automated (presumably not thoroughly checked by a human) tool on regular expressions, as they can only approximate the syntax of most programming languages.虽然上述 Vim 命令适用于偶尔的战术编辑,但我不会基于正则表达式建立自动化(大概没有经过人工检查)工具,因为它们只能近似于大多数编程语言的语法。 It's fine for Vim's syntax highlighting, where you can live with the occasional misrepresentation. Vim 的语法突出显示很好,您可以忍受偶尔的误传。 It's something different to directly work on the source code itself.直接处理源代码本身是不同的。 For that, there are better tools that directly implement the language's syntax rules (usually not via regular expressions, but a full-blown and tested parser).为此,有更好的工具可以直接实现语言的语法规则(通常不是通过正则表达式,而是一个成熟且经过测试的解析器)。 You don't mention the language, but a quick search for «language» linter or «language» code style check should give you something to start.您没有提到语言,但是快速搜索«language» linter«language» 代码样式检查应该会给你一些开始。

试试这个 vim 自动化表达式:

:%s/\vif\((.*)\)/if ( \1 )/gc

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

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