iOS中的正则表达式 [英] regular expression in iOS

查看:125
本文介绍了iOS中的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个正则表达式来匹配以下 -100..100:0.01 。这个表达式的含义是该值可以增加0.01,并且应该在-100到100的范围内。

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 be in the range -100 to 100.

任何帮助?

推荐答案

您可以使用 NSRegularExpression 代替。它确实支持 \ b ,顺便说一句,但你必须在字符串中转义它:

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

虽然,我认为 \\W 会是一个更好的主意,因为 \\b 会在数字上检测到负号。

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

一个希望更好的例子:

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. :)

编辑:根据以下评论修正。

fixed based on the below comment.

这篇关于iOS中的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆