-1

I need to get some hash variable value from html page content. It looks like this:

//...html code...
var somehash = '12d51e50f4';
//...html code...

How to get value in quotes using Regexp or something else?

Timur Mustafaev
  • 4,869
  • 9
  • 63
  • 109
  • Nothing :D I don't know how to use regexp in Objective-c :) – Timur Mustafaev Sep 06 '11 at 14:11
  • 3
    Well start by reading the docs to get familiar with it, and give it an honest try. Edit your question with what you came up with if it doesn't work like you want it. There are literally hundreds of questions with regex examples just on this site. – Mat Sep 06 '11 at 14:14
  • Here's the link you'll want: http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html – Rob Napier Sep 06 '11 at 14:17
  • Once someone asks about html "parsing" via regex, there should be a link to this answer: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454 – vikingosegundo Sep 06 '11 at 15:28

2 Answers2

2

This is the regex pattern that would match the specified line of code and extract the hash value into the first capturing group:

\bvar\s+somehash\s*=\s*'([0-9A-F]+)';

nikuco
  • 221
  • 2
  • 8
1

@Timur is right in that before asking this type of question you should really read the documentation. That said, here is one way of doing what you ask. You might want to tweak the regular expression for your specific needs. This code was compiled in a commandline tool linking only with the Foundation framework:

int main (int argc, const char * argv[])
{
    @autoreleasepool {
        NSString *html = @"<html>\n<head>\n<title>Test</title>\n</head>\n<body>var someHash = '123abc';</body></html>";
        NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:@"var someHash = '(\\w*)';" options:NSRegularExpressionCaseInsensitive error:NULL];
        NSTextCheckingResult *match = [regexp firstMatchInString:html options:0 range:NSMakeRange(0, html.length)];
        if (match) {
            NSRange  hashRange = [match rangeAtIndex:1];
            NSString *hashCode = [html substringWithRange:hashRange];
            NSLog(@"Hash Code is %@", hashCode);
        }
    }
    return 0;
}

For production code you will want to check for errors.

aLevelOfIndirection
  • 3,522
  • 14
  • 18