regular expression in iOS

前端 未结 4 1337
清酒与你
清酒与你 2020-12-06 05:44

I am looking for a regular expression to match the following -100..100:0.01. The meaning of this expression is that the value can increment by 0.01 and should b

4条回答
  •  情歌与酒
    2020-12-06 06:13

    You could use NSRegularExpression instead. It does support \b, btw, though you have to escape it in the string:

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

    Though, I think \\W would be a better idea, since \\b messes up detecting the negative sign on the number.

    A hopefully better 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];
    

    I hope this helps. :)

    EDIT: fixed based on the below comment.

提交回复
热议问题