2014-03-28 26 views
0

數據我用客觀的C創建一個程序,將使用正則表達式一個HTML文件中拉出來的數據。唯一對該程序很重要的行包含文本popupName,我也需要從它中規定所有HTML標記。這可以用一個正則表達式來完成嗎?Objective C的正則表達式摘自線包含文本

到目前爲止,我一直在使用popupName找到我要找的線,然後刪除所有匹配<[^>]*>

難道這兩個操作可以合併成一個?

這裏的例子輸入:

  <div> 
       <div class="popupName"> Bob Smith</div> 
       <div class="popupTitle"> 
        <i></i> 
       </div> 
       <br /> 
       <div class="popupTitle"></div> 
       <div class="popupLink"><a href="mailto:"></a></div> 
      </div> 

,從我想只提取 「鮑勃·史密斯」。除此之外,我會多次出現這樣的行名稱。

+0

如何顯示了關於你在說什麼行代碼;這裏沒有人是心智讀者(據稱)。 –

+0

@我是你的意思是嗎? – 735Tesla

+0

是的,正好:) –

回答

1

你的模式是非常接近你可能會用另外的希望:

"popupName">(.*)|<[^>]*> 

添加「popupName」後跟一個捕獲組將讓您抓住你想要的特定信息。

在Objective-C:

NSString* searchText = @"<div><div class=\"popupName\"> Bob Smith</div><div class=\"popupTitle\"><i></i></div><br /><div class=\"popupTitle\"></div><div class=\"popupLink\"><a href=\"mailto:\"></a></div></div><div>"; 
NSString *pattern = @"\"popupName\">(.*)|<[^>]*>"; 
NSRange searchRange = NSMakeRange(0, [searchText length]); 

NSError *error = NULL; 
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error]; 
NSString *results = [regex stringByReplacingMatchesInString:searchText options:0 range:searchRange withTemplate:@"$1"]; 

NSLog(@"results: %@",results); 

結果:

results: Bob Smith 
0

我一直在玩這個了一點,但我使用javascript和不能做一個積極的回顧後。但是,如果你的目標C可以讓你做出積極的向後看和積極的向前看,你應該能夠做到這一點。

+0

你有沒有一個例子? – 735Tesla

+0

像一個正則表達式的例子?它是否符合客觀的要求並不重要。 – 735Tesla