【问题标题】:VS Code search and replace and change line order VuejsVS Code 搜索替换和更改行顺序 Vuejs
【发布时间】:2020-11-26 18:29:38
【问题描述】:

我有这个标签出现在多个文件中 - 相同的路径但具有不同的图像文件:

<img 
        id="logo"            
        style="margin-left:170px;margin-top:8px;width:85px"
        class="shrunk"
        src="~/static/img/poweredby-grey.png"
        alt=" logo" 
      >

我想在任何地方替换 src 行,但我还需要按顺序移动新的 :src 行,因为 Vue js linter 会说 :src 需要在类和样式之前。

<img 
        id="logo"
        :src="require('~/static/' + imgURL + '/poweredby-grey.png')"            
        style="margin-left:170px;margin-top:8px;width:85px"
        class="shrunk"             
        alt=" logo" 
      >

我使用了正则表达式替换并且能够将 src 行替换为正确的 :src 行。鉴于我有大约 100 个文件要执行此操作,我如何在 VS Code 中快速执行此操作?

我目前的搜索和替换正则表达式是:

 src="~/static/img/(.+?)"
 :src="require('~/static/' + imgURL + '/$1')"

如何调整这两个正则表达式来搜索和替换整个 &lt;img&gt; 标记 - 这样在我的替换正则表达式中我同时更正了行顺序。

非常感谢。

【问题讨论】:

  • 使用这个作为搜索字符串 - (&lt;img[\s\r?\n]+id.*?)([\r?\n\s]+style.+)([\r?\n\s]+class.+)+([\r?\n\s]+src.+)([\r?\n\s]+alt.+)[\r?\n\s]+&gt; 你可以试试这个吗?我相信这些属性的顺序与您在示例中提到的顺序相同.....将其用作替换字符串$1$4$3$2$5&gt; - 我对其进行了测试,它似乎有效。让我知道你的情况如何。如果运行良好,那么它会更改行的顺序,下一步您可以运行正则表达式来替换 src

标签: regex vue.js visual-studio-code


【解决方案1】:

我想Multiline search 可以在这里为您提供帮助。您可以为不同的属性创建组,然后重新排列它。 VS Code 的 Search Editor 功能与此 experimental plugin 结合使用可能会有所帮助。

但是,如果有其他选择,我不建议使用正则表达式进行此类转换。 最好的方法是使用规则的自动修复选项(如果有的话)。我怀疑是这条规则给你一个错误:attributes-order。在这种情况下,您可以简单地运行带有--fix 标志的eslint,它会自动重新排序道具。

【讨论】:

    【解决方案2】:

    让您的正则表达式更简单的一种方法是连续运行两个查找和替换。使用 Replace Rules 之类的扩展程序可以做到这一点。

    在您的 settings.json 中:

      "replacerules.rules": {
    
        "editImgSrc": {
          "find": "src=\"~/static/img/(.*?)\"",
          "replace": ":src=\"require('~/static/' + imgURL + '/$1')\""
        },
         "reorder vueImgSrc": {
                                                  // get the src line and the two preceding lines
          "find": "((.*\r?\n){2})( *:src=\"require.*\r?\n)", 
          "replace": "$3$1"                                       // reorder them
        },
      },
    
      "replacerules.rulesets": {                // bundle the 2 find/replaces into one ruleset
      
        "Replace with vueImgSrc and reorder": {
          "rules": [
            "editImgSrc",
            "reorder vueImgSrc"
          ]
        }
      },
    

    然后是一个键绑定来运行它(在 keybindings.json 中):

      {
        "key": "alt+w",                         // whatever keybinding you want
        "command": "replacerules.runRuleset",
        "when": "editorTextFocus && !editorReadonly",
        "args": {
            "rulesetName": "Replace with vueImgSrc and reorder"
        }
      },
    

    【讨论】:

      猜你喜欢
      • 2023-02-11
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      相关资源
      最近更新 更多