Lizza
Lizza

Reputation: 2819

How can I search for and remove an escaped character from an NSString?

I am reading a line of code in from a source file on disk and the line is a string, and it is of a string that contains HTML code in it:

line = @"format = @"<td width=\"%@\">";"

I need to remove the escaped characters from the html string. So any place that there is a '\"', I need to replace it with ''. I tried this:

[line stringByReplacingOccurrencesOfString:@"\\""" withString:@""];

But it only removed the '\' character, not the accompanying '"'. How can I remove the escaped '"' from this string?

EDIT: The key part of this problem is that I need to figure out a way to identify the location of the first @", and the closing " of the string declaration, and ignore/remove everything else. If there is a better way to accomplish this I am all ears.

Upvotes: 3

Views: 2204

Answers (2)

jscs
jscs

Reputation: 64022

[s stringByReplacingOccurrencesOfString:@"\\\"" withString:@""]

The replacement string there is a slash, which has to be escaped in the literal replacement string using another slash, followed by a quote, which also has to be escaped in the literal by a slash.

Upvotes: 2

Javi Campa&#241;a
Javi Campa&#241;a

Reputation: 1481

Try use this:

NSString *unfilteredString = @"!@#$%^&*()_+|abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
NSCharacterSet *notAllowedChars = [[NSCharacterSet characterSetWithCharactersInString:@"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"] invertedSet];
NSString *resultString = [[unfilteredString componentsSeparatedByCharactersInSet:notAllowedChars] componentsJoinedByString:@""];
NSLog (@"Result: %@", resultString);

Upvotes: -1

Related Questions