Reputation: 75
Trying to capitalize all tags and running into trouble with substitution. Any idea why "upperCaseString" method isn't working?
NSError *error = nil;
NSMutableString *stringToCap = [NSMutableString stringWithString:@"<kaboom>stuff</kaboom>"];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(</?[a-zA-Z].*?>)" options:NSRegularExpressionCaseInsensitive error:&error];
NSMutableString *modifiedString = [NSMutableString stringWithString:[regex stringByReplacingMatchesInString:stringToCap options:0 range:NSMakeRange(0, [stringToCap length]) withTemplate:@"$1".uppercaseString]];
NSLog(@"%@", modifiedString);
Produces: <kaboom>stuff</kaboom>
when I expect <KABOOM>stuff</KABOOM>
Upvotes: 1
Views: 51
Reputation: 53000
stringByReplacingMatchesInString:options:range:withTemplate:
doesn't work like that, the type of the last argument is just NSString
and the string you are passing is the result of the expression @"$1".uppercaseString
– which is just @"$1"
.
A possible algorithm (pseudo code):
for NSTextCheckingResult *match in [regex matchesInString:... options:... range:...] do
extract the substring at match.range from modified string
uppercase it
replace the substring at match.range with uppercased result
Upvotes: 1