简体   繁体   中英

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. Unfortunately the Java regular expressions API is a lot different from the Objective C API.

I am trying to use the NSRegularExpression class to evaluate the regular expressions. In Java this is completely different: you have to use the Pattern and Matcher classes.

There is something I can't figure out (among other things). What is the equivalent of Matcher.lookingAt() in Objective C? To put it in code. What would be the Objective C translation of the following code?

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)

I figured it out! This is the NSRegularExpression equivalent of the Java code:

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! The docs say:

NSMatchingAnchored Specifies that matches are limited to those at the start of the search range. See enumerateMatchesInString:options:range:usingBlock: for a description of the constant in context.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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