ios 正则表达式

浏览 : 7594 次 Wed, 05 Nov 2014 14:19:30 GMT

1 【-100,100】之间最多带两位小数的数,例如:-100, -100.0, -99.1, ...

 

NSString *string = <...your source string...>;
NSError  *error  = NULL;

NSRegularExpression *regex = [NSRegularExpression 
  regularExpressionWithPattern:@"\\W-?1?[0-9]{2}(\\.[0-9]{1,2})?\\W"
                       options:0
                         error:&error];

NSRange range   = [regex rangeOfFirstMatchInString:string
                              options:0 
                              range:NSMakeRange(0, [string length])];
NSString *result = [string substringWithRange:range];
(\b|-)(100(\.0+)?|[1-9]?[0-9](\.[0-9]{1,2})?\b

 

Explanation:

(\b|-)      # word boundary or -
(           # Either match
 100        #  100
 (\.0+)?    #  optionally followed by .00....
|           # or match
 [1-9]?     #  optional "tens" digit
 [0-9]      #  required "ones" digit
 (          #  Try to match
  \.        #   a dot
  [0-9]{1,2}#   followed by one or two digits
 )?         #   all of this optionally
)           # End of alternation
\b          # Match a word boundary (make sure the number stops here).