regex - Find and replace comma-separated strings to Cassandra list format in VIM -
i convert comma-separated string quoted "" such following:
"hello,world,stack,overflow" into following cassandra list format using vim:
"['hello','world','stack','overflow']" where each element embraced '' , whole original string embraced "[]". can know how should in vim?
in input, such comma-separated string quoted "" part of csv formatted row. below example:
other,fields,123,456,"hello,world,stack,overflow" second,row,567,890,"another,comma,separated,string" ... and transform into:
other,fields,123,456,"['hello','world','stack','overflow']" second,row,567,890,"['another','comma','separated','string']" ... and each of target strings won't across multiple lines.
try this
:%s/\v(".*)@<=\s*([^,"]+)\s*(.*")@=/'\2'/g :%s/"/"[ :%s/"\[\@!/]" or @ once
:%s/\v(".*)@<=\s*([^,"]+)\s*(.*")@=/'\2'/ge | %s/"/"[/e | %s/"\[\@!/]" this works on example. not work if there more 1 pair of quotes on line.
explanation
:%s/\v(".*)@<=\s*([^,"]+)\s*(.*")@=/'\2'/g this looks string has quote before , after lookaheads , lookbehinds. capture isn't comma or quote , replace captured part in single quotes. throws out leading or trailing spaces.
:%s/"/"[ this should self explanatory if have used :s before
:%s/"\[\@!/]" this uses negative lookahead find first quote isn't followed left bracket , replaces right bracket , quote.
after thinking bit more think can whole file in 1 shot regardless of weather there more 1 pair of quotes on line.
the first function helper function makes substitute command little easier type. (you have done 3 substitute commands in single line have been ugly). same thing stuff above.
function! replacecommaseperated(string) let l:tmp = substitute(a:string, '[^,"]\+', "'\\0'", 'g') let l:tmp = substitute(l:tmp, '"', '"[', '') return substitute(l:tmp, '"\[\@!', ']"', '') endfunction function! runcommareplace() %s/".\{-}"/\=replacecommaseperated(submatch(0))/g endfunction the second function finds quoted strings , passes off function , gets replaced @ once. , know 1 beginning , end quotes because there guaranteed 1 pair of quotes.
the reason works , regex parser doesn't confused pattern matching starts after end of first match. if had string " " b " c "
" " first match , " c " second match because when parser tried match after b see b " c " , doesn't match.
to run in vim copy 2 function vimrc. , in file want run run following command.
:call runcommareplace()
Comments
Post a Comment