开发者

NSRegularExpression and capture groups on iphone

I need a little kickstart on regex on the iphone. Basically I have a list of dates in a private MediaWiki in the form of

*185 BC: SOME EVENT HERE

*2001: SOME OTHER EVENT MUCH LATER

I now want to parse that into an Object that has a NSDate property and a -say- NSString property. I have this so far: (rawContentString contains the mediawiki syntax of the page)

NSString* regexString =@"\\*( *[0-9]{1,}.*): (.*)";
NSRegularExpressionOptions options = NSRegularExpressionCaseInsensitive;
NSError* error = NULL;

NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:regexString options:options error:&error];
if (error) {
  开发者_如何学Python  NSLog(@"%@", [error description]);
}

NSArray* results = [regex matchesInString:rawContentString options:0 range:NSMakeRange(0, [rawContentString length])];
for (NSTextCheckingResult* result in results) {

    NSString* resultString = [rawContentString substringWithRange:result.range];
    NSLog(@"%@",resultString);
}

unfortunately I think the regex is not working the way I hope and I dont know how to capture the matched date and text. Any help would be great. BTW: there is not by any chance a regex Pattern compilation for MediaWiki Syntax out there somewhere ?

Thanks in advance Heiko *


My issue was that I was using matchesInString and I needed to use firstMatchInString because it returns multiple ranges in a single NSTextCheckingResult.

This is counter intuitive, but it worked.

I got the answer from http://snipplr.com/view/63340/

My Code (to parse credit card track data):

NSRegularExpression *track1Pattern = [NSRegularExpression regularExpressionWithPattern:@"%.(.+?)\\^(.+?)\\^([0-9]{2})([0-9]{2}).+?\\?." options:NSRegularExpressionCaseInsensitive error:&error];

NSTextCheckingResult *result = [track1Pattern firstMatchInString:trackString options:NSMatchingReportCompletion range:NSMakeRange(0, trackString.length)];

self.cardNumber = [trackString substringWithRange: [result rangeAtIndex:1]];
self.cardHolderName = [trackString substringWithRange: [result rangeAtIndex:2]];
self.expirationMonth = [trackString substringWithRange: [result rangeAtIndex:3]];
self.expirationYear = [trackString substringWithRange: [result rangeAtIndex:4]];


As for the regex, i think something around these lines:

\*([ 0-9]{1,}.*):(.*)

should work better to what you need. You're not escaping the first *, and why is there a * in the first group statement?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜