regex - Vim 匹配除行首字符之外的所有内容

标签 regex vim

我已经广泛搜索了这个问题的答案,但在任何地方都找不到。我想用一行(使用搜索和替换)或其他命令替换功能 block 中的所有代码。我还希望能够对整个文件中的多个函数执行此操作。

我有一段这样的代码......

{
some code
more code...
many lines of random code
}

我想用一行代码替换大括号内的所有内容,例如:

{
return STATUS_OK;
}

我尝试过类似的方法,

%s/^{_[^}]+/\treturn STATUS_OK;/g

但这会在行首的第一个 } 处停止,而不是在行首的第一个 } 处停止。

我试过了

%s/^{_[^^}]+/\treturn STATUS_OK;/g

为了在行首的第一个 } 处停止,但由于某种原因这不起作用。有任何想法吗?谢谢。

最佳答案

此正则表达式匹配最外层的花括号,而不考虑函数名称:

 %s/^{\(\(\s\+}\)\|[^}]\|\_s\)*/{\treturn STATUS_OK;/g

分割:

^{  # match a curly at the beginning of a line
\(  # group these alternations.... either match
     \(\s\+}\) \|  # whilespace followed by a closing curly 
                   # (to get rid of internal blocks) or ..
     [^}]      \|  # match a non curly, or ..
     \_s           # match newlines and whitespaces
 \)*               # match the alternation as long as you can

关于regex - Vim 匹配除行首字符之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19815814/

相关文章:

javascript - 正则表达式去除所有 html 标签,不包括 <br> & <a class ='user' ></a>

regex - 如何在vim中合并奇数行和偶数行?

python - 无法安装 vim ubuntu 13.10

unicode - 如何在 vim 脚本中使用 Unicode 字符?

vimrc 文件只读时的不同颜色方案

mysql - 在 Mysql 中使用正则表达式替换

javascript - 正则表达式按单词或标签拆分

-999x999 的 javascript 正则表达式

regex - 谁有把 RegExp 翻译成 "natural language"的算法?

vim - 是什么设定了 vim 的历史?