0

In file whenever I am coming across (int or string)

id","type": "int"},
name","type":"string"}, 

I want to replace with

private int id
private String name

Need VI command which updates private [int | string] at beginning of line depending on end of the string.

migrated from stackoverflow.com Feb 11 '17 at 12:12

This question came from our site for professional and enthusiast programmers.

1

You could do this with capture groups:

:%s/\v(.{-})".*(int|string)"},$/private \2 \1
:g/^\Cprivate string/normal w~

The parentheses create two "capture groups", the contents of which are then used in the replacement string.

The second line simply corrects the case of "string" to "String".

The first command, in detail:

  • %s/foo/bar: This is a substitute command that replaces foo with bar.
  • In the command above, foo is the pattern we search for. In our command, this is \v(.{-})".*(int|string)"},$ This breaks down as:
    • \v: This turns on "very-magic" mode, which allows us to use more powerful regular-expression features without having to escape a lot of characters,
    • (.{-}) This is the first capture group, and matches everything on the line up to the first ",
    • " This matches the first " on the line,
    • .* This matches everything up to the int or string
    • (int|string) This is the second capture group, and matches either int or string
    • "},$ This matches the remainder of the line, to ensure the int/string was actually at the end of the line
  • bar is the replacement text we use. In our command, this is private \2 \1. The \1 and \2 are replaced with the contents of the two captured groups.

You might need to tweak this if the contents of the lines you are searching for do not precisely match what you pasted in the question. e.g. If the lines really look like this:

{"lots","of","other","stuff","id","type": "int"},

You'd could use the following command:

%s/\v.*"([^"]{-})","[^"]{-}": "(int|string)"},$/private \2 \1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.