iOS中的正则表达式

Can*_*non 14 regex ios

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

有帮助吗?

小智 30

你可以NSRegularExpression改用.它支持\b,顺便说一下,虽然你必须在字符串中转义它:

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

虽然,我认为\\W这是一个更好的主意,因为\\b搞砸了检测数字上的负号.

一个希望更好的例子:

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];
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助.:)

编辑:基于以下评论修复.

  • `NSRange*range`应该是`NSRange range` (2认同)

Tim*_*ker 10

(\b|-)(100(\.0+)?|[1-9]?[0-9](\.[0-9]{1,2})?\b
Run Code Online (Sandbox Code Playgroud)

说明:

(\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).
Run Code Online (Sandbox Code Playgroud)