[ACCEPTED]-Regular Expression to replace " {" with "(newline){" in xcode-xcode

Accepted answer
Score: 61

You could try the following:

  • In the Find box, type space \ { $
  • In the Replace box, type control+q return {

control+q is needed to 14 quote the return key. There’s no visual 13 feedback for typing control+q return, so the only visible 12 character in the replace box is the opening 11 curly brace:

Screenshot Find & Replace

Although this answers your question, there’s 10 (at least!) one problem: it won’t indent 9 the opening curly brace, so something like

- (void)method {
    for (obj in collection) {
        NSLog(@"%@", obj);
    }
}

is 8 converted to

- (void)method
{
    for (obj in collection)
{
        NSLog(@"%@", obj);
    }
}

The menu item Edit > Format 7 > Re-Indent will place the opening curly 6 braces in the correct indentation tab but 5 there might be non-desired side effects 4 to your code style.


Edit: as commented in the 3 other answer, you might want a regular expression 2 that matches an arbitrary number of whitespaces 1 surrounding the curly brace, e.g. \s*{\s*$

Score: 4

Just copy an example of needed replacement 2 string (new line or else) from code to replacement 1 box.

Score: 2

search for this \s\{ and replace with \n\{

Your editor 14 needs to support regular expressions in 13 both search and replace fields. If you 12 can't use the \n in the replace dialog because 11 it takes the string literally, try a option-enter 10 followed by {, that works in most editors 9 I tried.

  • the \s is a space character (if there could be more spaces you can use \s+)

note it has to be \s+ instead of \s* as 8 someone fixed because indeed \s* also matches 7 in case there is no space.

  • the \{ needs the backslash because {
    needs to be escaped as it has another meaning in a regex
  • the \n is for a newline

The best way however 6 would be to reformat your code where you 5 choose to have your { on a new line. Most 4 editors allow you to set these options.

Another 3 way is to use a code beautifier, you can 2 google these online and some allow to change 1 settings like that.

Score: 1

You can use [\n\r] to describe newline It's a shame, I 3 came across with that when I tap on magnifier 2 icon next to search bar while finding something 1 in a single file.

To see several other expressions:

  1. go to a file
  2. do cmd+f and open search
  3. tap on the magnifier icon at the left-hand side of search field at the top
  4. you can see other expressions in the dropdown menu
Score: 0

i searched a while to find out, that you 4 have to enable the find options for regular 3 expressions first on the small magnifier 2 glass in the left side of the find-input 1 field ;)

More Related questions