简体   繁体   English

等效于Objective C中Java的Matcher.lookingAt()

[英]Equivalent of Java's Matcher.lookingAt() in Objective C

I am porting a framework from Java to Objective C which heavily depends on regular expressions. 我正在将Java框架移植到目标C,而该框架在很大程度上依赖于正则表达式。 Unfortunately the Java regular expressions API is a lot different from the Objective C API. 不幸的是,Java正则表达式API与Objective C API有很多不同。

I am trying to use the NSRegularExpression class to evaluate the regular expressions. 我正在尝试使用NSRegularExpression类来评估正则表达式。 In Java this is completely different: you have to use the Pattern and Matcher classes. 在Java中,这是完全不同的:您必须使用Pattern和Matcher类。

There is something I can't figure out (among other things). 有些事情我不知道(除其他外)。 What is the equivalent of Matcher.lookingAt() in Objective C? 什么是目标C中的Matcher.lookingAt()? To put it in code. 放入代码中。 What would be the Objective C translation of the following code? 以下代码的Objective C翻译是什么?

Pattern pattern = Pattern.compile("[aZ]");
boolean lookingAt = pattern.matcher("abc").lookingAt();

Thanks to anyone who knows! 感谢任何认识的人! (btw the above example assigns true to the lookingAt boolean) (顺便说一句,上面的示例将true赋给lookingAt布尔值)

I figured it out! 我想到了! This is the NSRegularExpression equivalent of the Java code: 这是与JavaRegularExpression等效的Java代码:

NSError *error = nil;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"[aZ]" options:0 error:&error];
if (error) {
    // Do something when an error occurs
}
NSString *candidate = @"abc";
BOOL lookingAt = [expression numberOfMatchesInString:candidate options:NSMatchingAnchored range:NSMakeRange(0, candidate.length)] > 0;

The emphasis here lies on the NSMatchingAnchored option when executing the expression! 这里的重点在于执行表达式时的NSMatchingAnchored选项! The docs say: 文档说:

NSMatchingAnchored Specifies that matches are limited to those at the start of the search range. NSMatchingAnchored指定将匹配项限制为搜索范围开始时的匹配项。 See enumerateMatchesInString:options:range:usingBlock: for a description of the constant in context. 有关上下文中常量的描述,请参见enumerateMatchesInString:options:range:usingBlock:。

That's exactly what I was looking for! 这正是我想要的!

You may do something like 你可能会做类似的事情

NSString *regex = @"ObjC";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@", regex]; 

if( [predicate evaluateWithObject:myString]) 
    NSLog(@"matches");
else
    NSLog(@"does not match");

take a look at Predicate Format String Syntax guide for further options. 参阅谓词格式字符串语法指南以了解更多选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM