How to enumerate all named captures in RegexKit?
I recently wanted use regex in Cocoa app. But I found that Cocoa does not include a regex class. So I decided to use RegexKit (OgreKit is good, but I don't know why it did not run fine on my OSX 10.6.4 x86_64).
I have a file content like:
12:20:30 - 01:20:30 some text 11:20:30 - 04:20:30 some text
And I want to pick up all time values and text values.I found this example code in a guide:
NSString *entireMatchString = NULL, *totalString = NULL, *dollarsString = NULL, *centsString = NULL;
NSString *regexString = @"owe:\\s*\\$?(?<total>(?<dollars>\\d+)\\.(?<cents>\\d+))";
[@"You owe: 1234.56 (tip not included)" getCapturesWithRegexAndReferences:regexString,@"$0", &entireString,@"${total}", &totalString,@"${dollars}", &dollarsString,@"${cents}",¢sString,nil];
// entireString = @"owe: 1234.56";
// totalString = @"1234.56";
// 开发者_运维知识库dollarsString = @"1234";
// centsString = @"56";
So I wrote a regex string
NSString *regexString = @"\\s*\\n*(?<start>\\d\\d:\\d\\d:\\d\\d*)\\s*-\\s*(?<end>\\d\\d:\\d\\d:\\d\\d*)\\s*\\n*(?<text>.*)
and it worked fine, but it only works once. I need to pick up all named captures, like we do in Ogrekit, e.g.:
OGRegularExpression *regex = [OGRegularExpression regularExpressionWithString:@"<video src=\"(?<imageURL>.+)\".+>"
options:OgreCaptureGroupOption
syntax:OgreRubySyntax
escapeCharacter:OgreBackslashCharacter];
NSArray *matches = [regex allMatchesInString:@"<video src=\"http://test.com/hello.jpg\">"];
if (matches != nil && ([matches count] == 1))
{
OGRegularExpressionMatch *match = [matches objectAtIndex: 0];
NSString *result = [match substringNamed:@"ImageURL"];
// : http://test.com/hello.jpg
}
It's easy to find all named capture values from a matches array. Does someone know how to do in RegexKit? Thanks.
Take a look at the documentation under Enumerating all the Matches in a String by a Regular Expression. Specifically, you want to learn about the RKEnumerator class.
精彩评论