0

I am looking for a short and convenient way to extract a product's price from NSString. I have tried regular expressions, but always found some cases where did not match.

The price can be any number including decimals, 0 and -1 (valid prices: 10, 10.99, -1, 0).
NSString can contain a string like: @"Prod. price: $10.99"

Thanks!

user-123
  • 874
  • 1
  • 13
  • 34

3 Answers3

2

This will match all the examples you have given

-?\d+(\.\d{2})?

Optionally a -, followed by 1-many digits, optionally followed by a decimal point and 2 more digits.

If you've got other numbers that are not prices mixed in to the data then I don't think regex can fulfil your needs.

OGHaza
  • 4,795
  • 7
  • 23
  • 29
  • If I want not only 2 numbers after decimal, then change it to: -?(\d+)(\.\d+)? ? – user-123 Nov 18 '13 at 13:00
  • Why two capture groups? `(-?\d+\.\d+)?` – zaph Nov 18 '13 at 13:02
  • @Zaph, you're right that the first group doesn't need to be captured (we're taking the whole match not any of the capture groups anyway) - will change that now. The 2nd group is in brackets because the `?` applies to only the `\.\d{2}`. - I could make it a non-capturing group, but like I said, we're ignoring the groups anyway. – OGHaza Nov 18 '13 at 13:09
2
NSString *originalString = @"Prod. price: $10.99";

NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"-0123456789"];

[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
double number;
[scanner scanDouble:&number];

number is equal to 10.99

Obviously if you have other numbers before the value you looking for you wont find it.

string.Empty
  • 10,393
  • 4
  • 39
  • 67
0

Assuming that your NSString will always contain the price with $ prep-ended to it, the following regex will match your need

.*?\$(-?(\d+)(.\d{1,2})?)

Once the above regex is matched you can find out match.group(1) to be the price from the NSString.

Ramg
  • 160
  • 13