搜索并替换为带有修改的反向引用

Search and replace with backreference with modification

vim 高级用户的问题:

file1.txt

Some list
 - line 1
 - line 2

Example of payload:

```json
{
    "order_id": "ABC123",
    "postcode": "A1 B22",
    "items": [1, 2, 3]
}
```

More text follows.

我的目标是:

file2.txt

Some list
 - line 1
 - line 2

Example of payload:

    {
        "order_id": "ABC123",
        "postcode": "A1 B22",
        "items": [1, 2, 3]
    }

More text follows.

到目前为止,我设法通过非贪婪匹配 json 和反引号之间的所有内容:

%s/```json\(\_.\{-}\)```//g

但是在 </code> 的每一行前面加上一个完全不同的故事。</p> <p>我试验过的是:</p> <ul> <li>子匹配(即 <code>%s/```json\(\_.\{-}\)```/\=submatch(1)/g

  • 尝试链接替换(但我不知道该怎么做)
  • 任何help/suggestion?

    我会分两步完成:

    :g/```json/.,/```/s/^/    /
    :g/```/d
    

    第一步:

    • :g/<pattern>/<command> 在匹配 <pattern>.
    • 的每一行上执行 <command>
    • ```json就是我们的<pattern>,剩下的就是我们的<command>,一个简单的替换。
    • .,/```/是一个范围,涵盖了从当前行.到下一个```.
    • 行的每一行
    • s/^/ / 本质上是在该行前面加上 4 个空格。

    这有效地缩进了整个围栏块:

        ```json
        {
            "order_id": "ABC123",
            "postcode": "A1 B22",
            "items": [1, 2, 3]
        }
        ```
    

    第二步:

    • :g/<pattern>/<command> 在匹配 <pattern> 的每一行上执行 <command>,如上。
    • ``` 是我们的 <pattern>.
    • d 是我们的 <command>.

    这有效地删除了无关的围栏:

        {
            "order_id": "ABC123",
            "postcode": "A1 B22",
            "items": [1, 2, 3]
        }
    

    参见 :help :global