NSString:验证它是美国货币格式

Pru*_*goe 1 currency nsstring ios

有没有快速的方法来验证NSString是否格式化为美国货币?

所以我要确认的是字符0是$,以下字符是数字,除了string.length-3,它可以是小数(显示更改是可选的).

所以这通过1000美元,这通过1000美元,但这将失败1000美元.

谢谢

das*_*ght 9

一种简单的方法是使用此正则表达式验证字符串:

^[$][0-9]+([.][0-9]{2})?$
^ ^   ^  ^  ^   ^   ^  ^^
| |   |  |  |   |   |  ||
| |   |  |  |   |   |  |+-- End-of-input marker 
| |   |  |  |   |   |  +--- Optional
| |   |  |  |   |   +------ Repeated exactly two times
| |   |  |  |   +---------- A decimal digit
| |   |  |  +-------------- A dot (literal)
| |   |  +----------------- Repeated once or more
| |   +-------------------- A decimal digit
| +------------------------ The dollar sign (literal)
+-------------------------- Start-of-input marker
Run Code Online (Sandbox Code Playgroud)

以下是使用上述表达式的示例代码:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
    regularExpressionWithPattern:@"^[$][0-9]+([.][0-9]{2})?$"
                         options:NSRegularExpressionCaseInsensitive
                           error:&error];
if ([regex numberOfMatchesInString:@"$321.05" options:0 range:NSMakeRange(0, 7)]) {
    NSLog(@"Success");
}
Run Code Online (Sandbox Code Playgroud)