how to replace multi new line with single new line in Xcode using Find & Replace

In Xcode projects, we generally write programs without paying attention to line spacing.

So after coding is complete, how does one remove all those extra newlines with single line?

Upvotes: 12

Views: 6082

Answers (4)

rshev
rshev

Reputation: 4176

Modern Xcode (writing as of Xcode 11) DOES support multi-line regular expressions. Just add (?s) modifier before . to perform this type of search, e.g.:

Codable(?s).*rawValue will search for text blocks starting with Codable ending with rawValue regardless of how many lines they span.

Upvotes: 2

Luke
Luke

Reputation: 9690

I solved this by using a temporary string in its place. My problem was a little different, I wanted to find anywhere I had no blank line between a property and method declaration in an interface, like this:

@property (nonatomic) NSBlah *someThing;
- (id)someMethodThing;

And replace with:

@property (nonatomic) NSBlah *someThing;

- (id)someMethodThing;

In order to do this, I used this to find using multi-line:

@property(.*)\n([-+].*)

Then I replaced that with some text string in place of the newlines:

@property$1SOMETHINGWHATEVER123$2

Then, I switched off regex replace, and with regular text replace, replaced:

SOMETHINGWHATEVER123

With Xcode's newline character, which you can find by choosing Insert Pattern by clicking the magnifying glass (this is in Xcode 7):

enter image description here

This then replaces that SOMETHINGWHATEVER123 with two newlines, resulting in my multiline regex query being handled.

Not sure how directly applicable this is to your circumstances, given that this is so old, but I found my way here, so perhaps others might!

Upvotes: 4

Alex Gray
Alex Gray

Reputation: 16463

In the textual search field... one can do multiline / "non-printing character" search / replace by use of the following methods...

Say I wanted to replace all instances of

/**
 * This is a comment...

with

/**  This is a comment...

The "search term" would be entered as...

/**Alt/Option + EnterSpace*Space

and the replace term would be entered simply as...

/**Alt/Option + Tab

The moral of the story.. when you want to use characters that serve alternate purposes within the Search / Replace fields... combine the modifier Alt/Option with their entry to use them "literally".

Upvotes: 16

mmccomb
mmccomb

Reputation: 13807

XCode's find and replace does not support multi-line regular expressions.

If you want to search for multiple lines you'll need to set your search option to "Textual" and either type option+return twice or copy/paste in two new lines chars. Then replace with a single new line char.

See here for more information.

Upvotes: 12

Related Questions