regex - 在替换中使用 vim 的 printf

标签 regex vim

我正在尝试将日期格式从 月/日/年 2016 年 7 月 1 日

每行发生一次到 YYYY-mm-dd 00:00:00

我有搜索和参数部分工作,可以交换顺序等,

但是我想使用 vim 的 printf 来完成它并想出了以下...

%s/\(\d\+\)\/\(\d\+\)\/\(\d\+\)/\=printf('%d-%02d-%02d 00:00:00', \3, \1, \2)/

我明白了...

E15: Invalid expression: \3, \1, \2)
E116: Invalid arguments for function printf('%d-%02d-%02d 00:00:00', \3, \1, \2)

有什么想法吗?

最佳答案

你需要使用submatch()函数:

:%s/\(\d\+\)\/\(\d\+\)\/\(\d\+\)/\=printf('%d-%02d-%02d 00:00:00', submatch(3),
submatch(1), submatch(2))/

:help submatch()
submatch({nr}[, {list}])                                submatch()
                Only for an expression in a :substitute command or
                substitute() function.
                Returns the {nr}'th submatch of the matched text.  When {nr}
                is 0 the whole matched text is returned.
                Note that a NL in the string can stand for a line break of a
                multi-line match or a NUL character in the text.
                Also see sub-replace-expression.(...)

关于regex - 在替换中使用 vim 的 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41330466/

相关文章:

javascript - 将正则表达式中的组标记为可选

python - 正则表达式缺少匹配项

跨多行搜索并将它们复制到剪贴板

vim - 如何在 Vim quickfix 中控制错误输出格式?

regex - 查找仅匹配同一字符的两个实例的单词

regex - 要包含在正则表达式字边界中的连字符/破折号\b

php - 如何保存为 HTML 片段,而不是完整的 DOM 模型

vim - 如何获取事件 tmux 窗口的名称?

c - 如何在 vim 中对齐多个赋值

python - 预计python中有两个空行pep8警告