ios iOS中的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5478170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regular expression in iOS
提问by Cannon
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.
我正在寻找一个正则表达式来匹配以下内容-100..100:0.01
。此表达式的含义是该值可以递增 0.01,并且应在 -100 到 100 的范围内。
Any help ?
有什么帮助吗?
回答by SynTruth
You could use NSRegularExpression
instead. It does support \b
, btw, though you have to escape it in the string:
你可以用NSRegularExpression
。它确实支持\b
,顺便说一句,尽管您必须在字符串中对其进行转义:
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.
不过,我认为\\W
这是一个更好的主意,因为\\b
检测数字上的负号会搞砸。
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.
编辑:根据以下评论修复。
回答by Tim Pietzcker
(\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).
回答by CanSpice
Why do you want to use a regular expression? 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!
回答by Cannon
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 fine.. Thnx for the efforts guys !
工作正常..感谢你们的努力!