Setting up a snippet in Visual Studio Code with regex

一世执手 提交于 2019-12-01 09:48:49

问题


{
    "Comment": {
        "prefix": "#",
        "body":  "<!-- ${TM_FILEPATH/([^/]*\/[^/]*)$/$1/} -->"
    }
}

I have set up the about code snippet, the purpose is to add a comment that adds the file's base directory and file name <!-- templates/base.html --> like this but discards the rest of the path. I believe this is originally based on TextMate snippets.

I have tried everything but I can't get it to work, it's probably something silly but I don't see what I'm doing wrong.

Using just TM_FILEPATH
without the regex results in <!-- /Users/johndoe/Sites/blog/blog/templates/base.html -->

I used this https://code.visualstudio.com/docs/editor/userdefinedsnippets to find an example to base my code on. The example is this one:

${TM_FILENAME/(.*)\\..+$/$1/}
  |           |        | |
  |           |        | |-> no options
  |           |        |
  |           |        |-> references the contents of the first
  |           |             capture group
  |           |
  |           |-> regex to capture everything before
  |               the final `.suffix`
  |
  |-> resolves to the filename

Thanks to the ideas of the 2 commenters I was finally able to get it to work.

One commenter put me on track with the double backslashes to catch both Windows and Unix style slashes.

The other commenter suggested the square brackets.

Final result:

{
    "Comment": {
        "prefix": "#",
        "body":  "<!-- ${TM_FILEPATH/.*[\\/](.*[\\/].*)$/$1/} -->",
    }
}

回答1:


Let's try it with a character class that takes account of both path separator types and helps us to escape properly at the same time:

{
    "Comment": {
        "prefix": "#",
        "body":  [  
            "<!-- ${TM_FILEPATH/.*[\\/](.*[\\/].*)$$/$1/} -->",
        ]
    },
}



回答2:


Try something like this:

"Comment": {
    "prefix": "#",
    "body":  [

      "<!-- ${TM_FILEPATH/.*\\\\(.*\\\\.*)$$/$1/} -->",

      "<!-- ${TM_DIRECTORY/.*\\\\(.*)$/$1/}/${TM_FILENAME} -->",
    ]
},

Those two lines in the body should be equivalent. That works for the Windows directory style, like :

 c:\Users\Mark\asdf\experimental\src\js\main.js

Since your path.separators are / try something like:

"<!-- ${TM_FILEPATH/.*\/(.*\.*)$/$1/} -->", 
"<!-- ${TM_FILEPATH/.*\\/(.*\\.*)$/$1/} -->",
"<!-- ${TM_FILEPATH/.*\\\/(.*\\\.*)$/$1/} -->",
"<!-- ${TM_FILEPATH/.*\\\\/(.*\\\\.*)$/$1/} -->",

I just don't know how many backslashes you will need (and I can't test it here) for your OS.



来源:https://stackoverflow.com/questions/50688947/setting-up-a-snippet-in-visual-studio-code-with-regex

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