IOS regular expression

I am looking for a regex matching the following -100..100:0.01 . The meaning of this expression is that the value can increase by 0.01 and should be in the range from -100 to 100.

Any help?

+14
regex ios
Mar 29 '11 at 19:57
source share
4 answers

You can use NSRegularExpression . It supports \b , btw, although you need to avoid it on the line:

 NSString *regex = @"\\b-?1?[0-9]{2}(\\.[0-9]{1,2})?\\b"; 

Although, I think that \\W would be a better idea, since \\b prevent it from detecting a negative sign on the number.

Hope the best example:

 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]; 

Hope this helps. :)

EDIT: fixed based on the comment below.

+30
Sep 12 '11 at 19:13
source share
 (\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). 
+10
Mar 29 '11 at 20:16
source share

Why do you want to use regex? Why not just do something like (in pseudocode):

 is number between -100 and 100? yes: multiply number by 100 is number an integer? yes: you win! no: you don't win! no: you don't win! 
+2
Mar 29 2018-11-21T00:
source share
  if(val>= -100 && val <= 100) { NSString* valregex = @"^[+|-]*[0-9]*.[0-9]{1,2}"; NSPredicate* valtest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", valregex]; ret = [valtest evaluateWithObject:txtLastname.text]; if (!ret) { [alert setMessage:NSLocalizedString(@"More than 2 decimals", @"")]; [alert show]; } } 

works great .. thnx for effort guys!

+1
Mar 29 2018-11-21T00:
source share



All Articles