开发者

Text extraction with NSRegularExpression

开发者 https://www.devze.com 2023-02-04 16:54 出处:网络
Given a NSString *test = @\"...href=\"/functions?q=KEYWORD\\x26amp...\"; How can I extract the word KEYWORD from the string using NSRegularExpression?

Given a NSString *test = @"...href="/functions?q=KEYWORD\x26amp...";

How can I extract the word KEYWORD from the string using NSRegularExpression?

I have tried with the following NSRegularExpression on iOS SDK 4.2 but it is not able to find the text. Does the following code looks okay?

开发者_StackOverflow
NSRegularExpression *testRegex = [NSRegularExpression regularExpressionWithPattern:@"(?<=href=\"\\/functions\\?q=).+?(?=\\x26amp])" options:0 error:nil];
NSRange result = [testRegex rangeOfFirstMatchInString:test options:0 range:NSMakeRange(0, [test length])];


You have a stray "]" in your regex, right before the end, which is probably causing a problem. You also need to use four slashes to match a slash in the input string. (Double it to escape it in the C string, and then double again to escape it in the regex). I'd suggest two things. First, pass something in the error parameter and take a look at in it in the debugger. Second, I'm not a big fan of lookahead/lookbehind expressions. I think this style is more readable:

NSString *regexStr = @"href=\"\\/functions\\?=(.+?)\\\\x26amp";
NSError *error;
NSRegularExpression *testRegex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error];
if( testRegex == nil ) NSLog( @"Error making regex: %@", error );
NSTextCheckingResult *result = [testRegex firstMatchInString:test options:0 range:NSMakeRange(0, [test length])];
NSRange range = [result rangeAtIndex:1];
0

精彩评论

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