Reputation: 115
I am hoping to match multiple names within a document, but only match names after a certain string.
For example, the document:
Name: Tom
Name: Alex
Name: Karina
Name: Other Names
Name: Josh
Name: Sarah
Name: Mike
So I want to only match names that are after "Other Names". The intended output would be Josh, Sarah, Mike.
My current pattern: (?:Other Names)[\s\S]+([A-Za-z]+)
But it only returns the last name!
Upvotes: 4
Views: 407
Reputation: 734
name: *other *names\s*([a-zA-Z ]+)
the above regex will give ypu the exact result what you want. Use ignore case option
Upvotes: 0
Reputation: 626861
It can be achieved in Objective C since the regex flavor it supports is ICU (it supports the \G
operator):
(?:Name:\s+Other\s+Names\s*|(?!^)\G\s*)Name:\s+(\w+)
See the regex demo
The (?:Name:\s+Other\s+Names\s*|(?!^)\G\s*)
part will find the Name: Other Names
and (?!^)\G
will match the end of the previous successful match. Name:\s+(\w+)
will match Name:
+ whitespace(s) and capture into Group 1 the Name (if it consists of 1 word). If it contains more, just use .+
instead of \w+
.
See the Objective C demo:
NSError *error = nil;
NSString *pattern = @"(?:Name:\\s+Other\\s+Names\\s*|(?!^)\\G\\s*)Name:\\s+(\\w+)";
NSString *string = @"Name: Tom\nName: Alex\nName: Karina\nName: Other Names\nName: Josh\nName: Sarah\nName: Mike";
NSRange range = NSMakeRange(0, string.length);
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSArray *matches = [regex matchesInString:string options:0 range:range];
for (NSTextCheckingResult* match in matches) {
NSRange group1 = [match rangeAtIndex:1];
NSLog(@"group1: %@", [string substringWithRange:group1]);
}
Upvotes: 1
Reputation: 1111
use this regex (?<=Other Names).*
NSString *text = @"Name: Tom Name: Alex Name: Karina Name: Other Names Name: Josh Name: Sarah Name: Mike";
NSString *pattern = @"(?<=Other Names).*";
NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:nil];
NSTextCheckingResult *match = [regularExpression firstMatchInString:text options:0 range:NSMakeRange(0, [text length])];
NSString *output = [text substringWithRange:[match rangeAtIndex:0]];
Upvotes: 0