How can i cover multiple matches for a single group in vscode find and replace?
my specific situation is converting an ton of arrays to objects like this
array: ['thing1', 'thing2', 'thing3'],
and convert it to something like this
objects: {
{
name: 'thing1',
},
{
name: 'thing2',
},
{
name: 'thing3',
},
}
the problem is with dealing with matching each of those groups, which there are varying array lengths so i cant just make 3 separate groups
my approach would be to script it...
I'm gonna guess python? #should have asked
old solution:
changed it to an argument you can pass on with your script
import sys
import re
def main(my_string):
#my_string = "array: ['thing1', 'thing2', 'thing3'],"
#this pattern will split on starts with whitespace or "["
pattern=r"[^\s?\[]*[']"
split_string = re.findall(pattern, txt)
result="objects: {\n"
for item in split_string:
result+="\t{\n"
result+=f"\t\tname: {item},\n"
result+="\t},\n"
result+="},\n"
print(result)
main(sys.argv[1]) #to read the argument from cmd
pattern test: https://regex101.com/r/omycdU/1
result:
python3 file.py "array: ['thing1', 'thing2', 'thing3'],"
objects: {
{
name: 'thing1',
},
{
name: 'thing2',
},
{
name: 'thing3',
},
},
new solution:
the new code is to send an entire file read line after line and adjust into the same format as you suggested. (result at the bottom)
import sys
import re
import fileinput
def main(my_file=""):
print(f"opening: {my_file}")
for line in fileinput.FileInput(my_file, inplace=True, backup='.bak'):
#this pattern looks for "whitespace" or "#" to skip this line if it is commented
#pattern=r"(^\s*#)|(^#)"
#test=bool(re.search(r"[:]\s[\[].*[\]],",line))
if not re.search(r"(^\s*#)|(^#)",line):
if re.search(r"[:]\s[\[].*[\]],",line):
result=find_and_replace(line)
print(line.replace(line, result), end='')
else:
print(line.rstrip())
else:
print(line.rstrip())
def find_and_replace(my_string):
#this pattern will split on starts with "whitespace" or "["
pattern=r"[^\s?\[]*[']"
split_string = re.findall(pattern, my_string)
result="objects: {\n"
for item in split_string:
result+="\t{\n"
result+=f"\t\tname: {item},\n"
result+="\t},\n"
result+="},\n"
#print(result)
return result
#main()
main(sys.argv[1])
regex1: https://regex101.com/r/7wtXWn/1
regex2: https://regex101.com/r/omycdU/1
result: (it is possible you need to rename to .txt if it are .py files)
python3 _Regex_loop_mytest_txt.py _mytest.txt
#my_string = "array: ['thing1', 'thing2', 'thing3'],"
#txt = "array: ['thing1', 'thing2', 'thing3'],"
txt = "array: ['thing1', 'thing2', 'thing3'],"
import sys
import re
import fileinput
#my_string = "array: ['thing1', 'thing2', 'thing3'],"
#txt = "array: ['thing1', 'thing2', 'thing3'],"
objects: {
{
name: 'thing1',
},
{
name: 'thing2',
},
{
name: 'thing3',
},
},
import sys
import re
import fileinput