Bhavik P. Bhavik P. - 1 month ago 18
Objective-C Question

How to Get Percentage From a NSString - Objective C

I would like to get a substring for a

NSString
that contains a percentage value.

For example:
1. Get 10% off with this item.
2. 55% off when you purchase this.

function should return 10% and 55% respectively.

I am using regex in Java
\\d+%


I don't know how to do the same in objective c.
I have searched it but I am a bit lost.

Answer

You should be able to use NSRegularExpression to execute the same regex that you use in java. There is a good tutorial for NSRegularExpression here.

https://www.raywenderlich.com/30288/nsregularexpression-tutorial-and-cheat-sheet

I was able to accomplish it with this code:

NSString *string = @"10% off with this item";

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\d+%" options:0 error:&error];
NSTextCheckingResult *result = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
NSString *substring = [string substringWithRange:result.range];


NSLog(@"%@", substring); // 10%

The key is in the TextCheckingResult. It contains the NSRange for the match in the original string so you can grab a substring of the match.

Comments