Search code examples
regexxcodereplacefind

Add quotation to start and end of each line in Xcode


I have multiple lists (in a .txt file) which I'd like to quickly convert to an array. I've seen this question asked and answered here for Notepad++, but not for Xcode. Is it possible to similarly here?

AliceBlue
AntiqueWhite
Aqua
Aquamarine
Azure
Beige
Bisque
Black
BlanchedAlmond

and convert it to an array literal...

var myArray = ["AliceBlue", "AntiqueWhite", ... ]

//the highest rated answer for this on the notepad++ thread: Add quotation at the start and end of each line in Notepad++ enter image description here

I should add I can use the expression (.+) in the find function, but not the "\1".


Solution

  • To add quotation marks to the start and end of every line with regular expressions in Xcode, choose the “Regular expression” search option and use a search regex of ^.*$ to “capture” the whole line (i.e., ^ is the start of the line, .* is zero or more of any character, and $ is the end of the line). You can then use a replacement regex of "$0" (i.e., a quotation mark, followed by capture group number zero, which was the original line, followed by a final quotation mark):

    enter image description here


    You can also use “multiple cursors”, a.k.a. multi-cursors. You can, for example, hold down the key and click-drag with your mouse, and then hit -◀︎ to go to the start of the lines, " for the opening quotation mark, -▶︎ to go to the end of the lines, and " for the closing quotation mark.

    enter image description here

    And while you can hold and and click-drag to make a bunch of multi-cursors, you can also toggle individual ones on and off with --clicks.


    If you want to remove the newline characters, too, with the regex approach, after doing the regex replacement, just go back to a normal “Contains” search and replace the “line break”, ⏎, with a comma and space:

    enter image description here

    Or, with the multi-cursor approach, after adding the quotation marks, go to the end of the line, add the comma and space, and hit the key to delete the line breaks:

    enter image description here

    You just need to delete the trailing comma at the very end.


    Obviously, no regex or multi-cursors are required when searching for line breaks. Just do a normal find-and-replace, replacing ⏎ with whatever you want, and then clean up the first and last entry:

    enter image description here