Bhavik P. Bhavik P. - 2 years ago 132
Objective-C Question

How to Get Percentage From a NSString - Objective C

I would like to get a substring for a

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

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

Answer Source

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.

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download