ios使用正则表达式在html中查找ID

时间:2012-12-19 06:56:11

标签: objective-c ios nsregularexpression

我使用NSRegularExpression查找HTML中包含40个字符的ID的出现

这里是我的代码:

 - (NSString *)stripOutHttp:(NSString *)string {

NSLog(@"the page content :: %@", string);

// Setup an NSError object to catch any failures
NSError *error = NULL;

// create the NSRegularExpression object and initialize it with a pattern
// the pattern will match any http or https url, with option case insensitive

//search for:: <input type="hidden" name="XID" value="f3f3fbafe552358d9312d1fe30670add09adc36c" />


NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<input type=\"hidden\" name=\"XID\" value\"?" options:NSRegularExpressionCaseInsensitive error:&error]; // ultimo funcional



// try /\b([a-f0-9]{40})\b/


// create an NSRange object using our regex object for the first match in the string 

NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])];

// check that our NSRange object is not equal to range of NSNotFound

if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) {
    // Since we know that we found a match, get the substring from the parent string by using our NSRange object

    NSString *substringForFirstMatch = [string substringWithRange:rangeOfFirstMatch];

    NSLog(@"Extracted data : %@",substringForFirstMatch);

    // return the matching string
    return substringForFirstMatch;
}

return NULL;
  }

所以我目前的正则表达式是:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<input type=\"hidden\" name=\"XID\" value\"?" options:NSRegularExpressionCaseInsensitive error:&error]; // ultimo funcional

我得到了我需要的一部分:

Extracted data : <input type="hidden" name="XID" value

现在如何获得任何40个字符值的响应?

我试过

// try /\b([a-f0-9]{40})\b/

但似乎还不明白如何使用它,

这是在::

之后的那种响应
<input type="hidden" name="XID" value="f3f3fbafe552358d9312d1fe30670add09adc36c" />

非常感谢

3 个答案:

答案 0 :(得分:2)

您应该考虑使用html或xml解析器解析整个问题(如Blender所说),但就目前而言,您的问题的答案如下:

 "<[^>]*id=DIVNAME.*?>(.*?)/>"

答案 1 :(得分:1)

正则表达式

 <input type=\"hidden\" name=\"XID\" value=\"([a-f0-9]{40})\"[\s]*/>

应与您的输入字符串匹配

我认为这不是最好的主意,但有一点,你可以使用很多空格,也可以使用任意空格。 如果我是你,我会查看html解析器库。

答案 2 :(得分:1)

请不要使用RegExes解析HTML。

请看这个重复的帖子:RegEx match open tags except XHTML self-contained tags