How to swap two words in Visual Studio Code with a find and replace?

孤人 提交于 2020-01-16 10:58:08

问题


The project I'm working on has a number of yaml files, where all the instances of lat: and long: need to be swapped, since the data is incorrectly labeled.

So for instance, the following:

- lat: "-82.645672"
  long: '44.941747'
  title: "Item 1"
- lat: "-82.645744"
  long: '44.940731'
  title: "Item 2"
- lat: "-82.645744"
  long: '44.940731'
  title: "Item 3"
- lat: "-82.646599"
  long: '44.941441'
  title: "Item 4"

Would need to look like this:

- long: "-82.645672"
  lat: '44.941747'
  title: "Item 1"
- long: "-82.645744"
  lat: '44.940731'
  title: "Item 2"
- long: "-82.645744"
  lat: '44.940731'
  title: "Item 3"
- long: "-82.646599"
  lat: '44.941441'
  title: "Item 4"

I'm struggling to figure out how to swap these two words globally. I looked at the plugins that are available, but they only seem to work with the current file you're editing, and when highlighting only a couple of words (i.e. like this one https://marketplace.visualstudio.com/items?itemName=davidmart.swap-word). I was looking into using regex as a possible solution, but can only find ways to reorder words on the same line. Is there a regex that can be used in a find and replace to swap two words that can get applied to all files in a project?


回答1:


Try this regex:

^(-\s+)(lat)(.*)(\n\s*)(long) // I made a small change here

and replace with:

$1$5$3$4$2

See regex101 demo.

This works perfectly fine for me in the find/replace widget but not in the search/replace across files panel. Why? See this "resolved" issue: issue: regex search and replace.

The issue seems to indicate it was provisionally "fixed" but it doesn't appear that it has been.

I was going to open a new issue but found this from earlier this week: issue: capture groups don't work when regex includes newline . So hopefully it will be fixed this iteration.

I am happy to report that this bug has been fixed in the Insiders Build 2019-09-16!! Demo below in Insider's Build:




回答2:


With the Replace Rules extension

  "replacerules.rules": {
    "Swap lat-long 1": {
      "find": ["lat","long"],
      "replace": ["XYZ","ABC"]
    },
    "Swap lat-long 2": {
      "find": ["XYZ","ABC"],
      "replace": ["long","lat"]
    }
  },
  "replacerules.rulesets": {
    "Swap lat-long": {
        "rules": [
            "Swap lat-long 1",
            "Swap lat-long 2"
        ]
    }
  }

Then execute command: Replace Rules: Run Ruleset...



来源:https://stackoverflow.com/questions/57964578/how-to-swap-two-words-in-visual-studio-code-with-a-find-and-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!