Reputation: 337
I need help with replacing occurrences of string with another string. Occurrency that needs to be detected is actually some kind of function:
%nx+a
or %nx-a
where x
and a
are some numbers.
So for example %n10+2
or %n54-11
.
I can't even use something like:
NSRange startRange = [snippetString rangeOfString:@"%n"];
because if I have two patterns within same string I'm checking I'll only get starting range of first one...
Thanks.
Upvotes: 0
Views: 170
Reputation: 2581
I assume that you need to do something with those two numbers. I think the best way is to use a regular expression to extract what you need in one go.
NSString * string = @"some %n5-3 string %n11+98";
NSError * regexError = nil;
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:@"%n(\\d+)([+-])(\\d+)"
options:0
error:®exError];
NSArray * matches = [regex matchesInString:string options:0 range:NSMakeRange(0, string.length)];
for (NSTextCheckingResult * match in matches) {
NSString * firstNumber = [string substringWithRange:[match rangeAtIndex:1]];
NSString * secondNumber = [string substringWithRange:[match rangeAtIndex:3]];
NSString * sign = [string substringWithRange:[match rangeAtIndex:2]];
// Do something useful with the numbers.
}
Of course if you just need to replace all the %n
occurences with a constant string you can do that in one call:
NSString * result = [string stringByReplacingOccurrencesOfString:@"%n\\d+[+-]\\d+"
withString:@"here be dragons"
options:NSRegularExpressionSearch
range:NSMakeRange(0, string.length)];
Disclaimer: I didn't test this code. Minor bugs may be present.
Upvotes: 1
Reputation: 740
Alter this code to match ur need
yourString = [yourString stringByReplacingOccurrencesOfString:@" +" withString:@" "options:NSRegularExpressionSearch range:NSMakeRange(0, yourString.length)];
Upvotes: -1
Reputation: 77661
For something like this you could use an NSRegularExpression
and use the method enumerateMatches:
.
Or you can create your own loop.
The first is the easiest once you have the correct pattern.
Something like...
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"%n" options:0 error:nil];
NSString *string = @"%n10+2*%n2";
[regex enumerateMatchesInString:string
options:0
range:NSMakeRange(0, string.length)
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
// here you will get each instance of a match to the pattern
}];
You will have to check the docs for NSRegularExpression
to learn how to do what work you need to do with this.
Upvotes: 2