Reputation: 777
I have a task with regular expressions. I have a list of NSRegularExpression
objects with different patterns. Also I have a NSString
object to define a source. I need to find which regular expression (from the given list) matches for the BEGINNING of source.
Is there a way to do it with Objective-C?
For example:
Expressions patterns
[a-z]
[A-Z]
[1-9]
source
Hello32
Result
Expression no 2 fits for the beginning of source, because of letter H
.
Upvotes: 0
Views: 267
Reputation: 81858
Why don't you just try them out?
NSString *testString = @"Hello";
NSArray *patterns = @[
@"[a-z]",
@"[A-Z]",
@"[1-9]",
];
for (NSString *pattern in patterns) {
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:NULL];
BOOL matchAtStart = [regex rangeOfFirstMatchInString:testString
options:0
range:(NSRange){0, testString.length}].location == 0;
NSLog(@"'%@': %@", pattern, @(matchAtStart));
}
Upvotes: 1
Reputation: 6511
You can prepend \A(?:
and append )
to each pattern to force them to match at the beggining of the string. The patterns provided as example would become:
\A(?:[a-z])
\A(?:[A-Z])
\A(?:[1-9])
\A
is an anchor to the beggining of the string (behaves exactly like ^
when the Multiline
flag is not set).Upvotes: 0