I’ve learning vim and am beginning to see just how powerful it is (especially combined with reg expressions).
Right now I’m trying to replace all integers in a python file with floating values.
E.g. you will com across things like [0, 0 , 0] that need to be[0.0, 0.0, 0.0]
The best I have now is:
:%s/\(\d+\)\@<=s*,/.0,/g
though I am producing results like 0.032.0
Two things:
- Can any of you regexperts whip up a robust way to solve the above problem?
- I’m starting to see how complicated these expressions can get. Is there anyway to say define the subregex for say an integer or a float in my .vimrc and have a way to embed it in later calls. e.g. a desired call might be :%s/\($(AnInt)\)+/-/g to change plus signs after integers into minuses.
(That or something equally modular)
Operating under the assumption that the results you’re getting “like 0.032.0” is because you started with 0.032
Caution, this is what happens when you try to force regular expressions and nothing else to parse non-regular languages. There are numerous edge cases where this regular expression fails. I will try to illustrate them as I go through.
:%s/\(\[.*\)\@<=\([0-9]\+\)\(,[^,]*\.[^,]*\)\@<!\.\@!\(.*\]\)\@=/\2.0/cgHow does this work?
First, I want to make sure that I’m within an array.
\(\[.*\)\@<=This is a lookbehind assertion searching for a literal
[This will fail on lists that are specified over multiple lines, and it will also fail in cases like this (it will match the 3 and the 4):
This makes a trade off for complexity. Please double check all matches to make sure you’re not doing something that you don’t intend.
Next, I want to actually match the text,
\([0-9]\+\)simple.Next, I want to make sure that there isn’t any dots before or after the numbers, but ignore things before and after commas.
\(,[^,]*\.[^,]*\)\@<!Next, I want to make sure there isn’t a literal period following the match.
\.\@!Finally, I want to make sure that there’s a literal
]somewhere after the match (to ensure I’m inside of an array.\(.*\]\)\@=Then last but not least I replace the found text with the second captured group and add a period.
As for your #2, no, but you can yank those areas into named paste buffers and use them at will. Use command edit mode
q: