【问题标题】:regexp objective-c. html parsing正则表达式目标-c。 html解析
【发布时间】:2011-09-06 14:07:15
【问题描述】:

我需要从 html 页面内容中获取一些散列变量值。它看起来像这样:

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

如何使用 Regexp 或其他方法获取引号中的值?

【问题讨论】:

  • Nothing :D 我不知道如何在 Objective-c 中使用正则表达式 :)
  • 首先阅读文档以熟悉它,然后诚实地尝试一下。如果它不像你想要的那样工作,请用你想出的东西来编辑你的问题。仅在这个网站上就有数百个关于正则表达式示例的问题。
  • 一旦有人通过正则表达式询问html“解析”,应该有一个指向这个答案的链接:stackoverflow.com/questions/1732348/…

标签: objective-c regex ios html-parsing


【解决方案1】:

这是匹配指定代码行并将哈希值提取到第一个捕获组的正则表达式模式:

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

【讨论】:

    【解决方案2】:

    @Timur 是正确的,在提出此类问题之前,您应该真正阅读文档。也就是说,这是按照您的要求做的一种方法。您可能希望根据您的特定需求调整正则表达式。此代码是在仅与 Foundation 框架链接的命令行工具中编译的:

    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;
    }
    

    对于生产代码,您需要检查错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 2021-07-20
      • 2014-12-06
      • 2012-09-12
      • 2014-05-16
      • 1970-01-01
      • 2013-07-23
      相关资源
      最近更新 更多