MrDatabase
MrDatabase

Reputation: 44445

Basic regex expression

I'd like to replace angle brackets and spaces in a string. For example @"< something >" goes to @"something". I'm currently trying:

NSString *s1 = @"< something >";
NSString *s2 =
[s1 stringByReplacingOccurrencesOfString:@"[<> ]"
                              withString:@""
                                 options:NSRegularExpressionSearch
                                   range:NSMakeRange(0, s1.length)];

However I'm brand new to regular expressions and @"[<> ]" doesn't seem to work. What's the correct regular expression to use to remove angle brackets and spaces?

Upvotes: 2

Views: 1727

Answers (2)

Jesse Black
Jesse Black

Reputation: 7976

Here is a solution that strips out the characters: '<','>',' '

NSCharacterSet*mySet = [NSCharacterSet characterSetWithCharactersInString:@"<> "];

NSString *s1 = @"< something >";

NSArray * components = [s1 componentsSeparatedByCharactersInSet:
                          mySet];
NSMutableString * formattedS1 = [NSMutableString string];
for (NSString * s in components) {
  [formattedS1 appendString:s];
}
NSLog(@"formatted string %@", formattedS1);

You can add whatever characters you need in the future to the first line

Upvotes: 1

Caleb
Caleb

Reputation: 124997

Note the documentation for NSRegularExpressionSearch:

You can use this option only with the rangeOfString:... methods.

So even if you had the right regex, you wouldn't be able to use it with this method.

For the situation you describe, it'll probably be easier to use -stringByTrimmingCharactersInSet: with a character set that includes '<' and ' '.

Update: Joshua Weinberg points out that you'd like to remove all occurrences of the characters '<', '>', and ' '. If that's the case, you'll want to look to NSRegularExpression's -stringByReplacingMatchesInString:options:range:withTemplate: method:

NSError *error = nil;
NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:@"<> " options:0 error:&error];
NSString *s1 = @"< something >";
NSRange range = NSMakeRange(0, s1.length);
NSString *s2 = [re stringByReplacingMatchesInString:s1 options:0 range:range withTemplate:@""];

(I haven't tested that, but it should point you in the right direction.)

Upvotes: 2

Related Questions