'Overwrite text with modifications or additions in VS Code

I wanted to use a function available in Intellij that allows to write this in java:

"Hello, World!".sout

And have it converted to:

System.out.println("Hello, World!);

But I can't find how to do this in Visual Studio Code, so this would be highly appreciated.

UPDATE: I just got to make some progress...

This is the result, but there's an error that says I'm missing a comma, I don't know what's wrong...

"Prints to console the given value": {
    "prefix": ".sout",
    "body": [
      "System.out.println("${TM_CURRENT_LINE/(\\S)[^(\\.)sout]}");" //${\S[^\.sout]}
    ],
    "description": "Prints to console the given value"
  }


Solution 1:[1]

Vscode allows you to customize code snippets, but you can't integrate existing fields like using methods. You can directly enter "sout" and then enter "Hello word" in parentheses to achieve this effect. At the same time, you can also click this to learn about custom code fragments, which will make your compilation faster and more comfortable

Solution 2:[2]

I think you will find it hard (or impossible) to create a snippet to do what you want. TM_CURRENT_LINE will get the value of the current line but it does not replace it, so it does not act as if you selected the line first. So the insertion point of your snippet is wherever the cursor is - which may be anywhere on that current line.

"System.out.println("${TM_CURRENT_LINE/(\\S)[^(\\.)sout]}");"

will not write System.out.println before anything on the current line (unless your cursor is at the very beginning), it will put that text wherever the cursor is located - in your case presumably at the very end of the line.

For reasons like that, I added the ability to run some commands before a find/replace in my extension: Find and Transform. You can achieve your desired result with this keybinding (in your keybindings.json):

{
  "key": "alt+y",                         // whatever keybinding you want
  "command": "findInCurrentFile",
  "args": {
    "preCommands": "cursorHomeSelect",    // start with cursor at end of line
    "replace": "System.out.println($1)",
    "isRegex": true,
    "restrictFind": "line"
  }
}

This will first select the line from your cursor to the beginning and then treat all that as a regex capture group 1.

The replace uses $1 to insert that selected text where you want it. Demo:

insert text after selecting the line

Solution 3:[3]

Why don't you use quick command sysout, which can also generate System.out.println() as you need.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mark
Solution 3 Mia Wu-MSFT