ElohmroW
ElohmroW

Reputation: 119

Remove trailing comma in vscode snippet transform

What I want

I am trying to transform this:

foo awehorihawolvbahvierwba3485y089726y216
bar :aw]\e[;r\a32[5a94t8g-09po

into this:

foo,
bar

The problem

My current solution is to remove the "junk" and replace it with a comma:

$1

${1/(\\w+).*/$1,/gm}

This however leaves a trailing comma and I find it annoying to remove the trailing comma every time.

foo,
bar,

What I've tried

Take the original idea and nest it into this transform

${<insert transform here>/,$//}

... like this ...

${${1/(\\w+).*/$1,/gm}/,$//}

Upvotes: 0

Views: 636

Answers (1)

Mark
Mark

Reputation: 182141

You appear to be triggering your snippet and then pasting your text into it, since you are only using $1 as your input. If that is not the case, let us know, it would probably be easy to modify this for a selection, etc.

This will work:

    "add a comma only if": {
        "prefix": ["py"],           // whatever prefix you want
        "body": [
            "${1/(\\w+).*(?=$(\r?\n)?)/$1${2:+,}/gm}"
            // "${1/(\\w+).*$(\r?\n)?/$1${2:+,\n}/gm}"  // this also works
        ]
    },

It will work for any number of input lines, putting a comma at the end of each except the last.

(?=$(\r?\n)?) positive lookahead for a newline, if so capture in group 2
${2:+,} if a group 2, add a comma

trailing comma demo

Upvotes: 1

Related Questions