问题
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!
回答1:
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.
回答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.
回答3:
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.
来源:https://stackoverflow.com/questions/20047566/extracting-price-from-string