本文介绍了使用正则表达式在Visual Studio Code中设置代码段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我已经建立了about代码段,目的是是添加一条注释,以添加文件的基本目录和文件名<!-templates / base.html->
,但丢弃其余的路径。我相信这最初是基于TextMate片段的。

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.

仅使用
TM_FILEPATH

不使用正则表达式将导致
<!--/ 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

感谢2位评论者的想法,我终于能够使它工作。

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

一个评论者让我用双反斜杠来跟踪Windows和Unix样式的斜杠。

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.

最终结果:

{
    "Comment": {
        "prefix": "#",
        "body":  "<!-- ${TM_FILEPATH/.*[\\/](.*[\\/].*)$/$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/} -->",
        ]
    },
}

这篇关于使用正则表达式在Visual Studio Code中设置代码段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 17:19
查看更多