[英]How to get text in a NSString that is in between two characters/words?
[英]Get text between two tags and make another NSString from it
我有這樣的帶有html代碼(NSString)的html頁面:
<html>
<p>
textA
</p>
<p>
textB
</p>
</html>
<a>
textC
</a>
我想在標簽之間獲取文本
並制作另一個NSString。 此代碼的預期結果是:
textAtextB
非常感謝你。
我不得不更換
[a]text[/a]
與
<a href="text">text</a>
這是我解決的方法:
NSString *xml = @"[a]text[/a][a]awesome[/a]"
NSString *pattern = @"\\[a\\](.*?)\\[\\/a\\]";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
for( NSTextCheckingResult *textCheckingResult in [regex matchesInString:xml options:0 range:NSMakeRange(0, xml.length)] )
{
NSRange matchRange = [textCheckingResult rangeAtIndex:1];
NSString *match = [xml substringWithRange:matchRange];
htmlString = [htmlString stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"[a]%@[/a]",match] withString:[NSString stringWithFormat:@"<a href=\"%@\">%@</a>",match,match] ];
NSLog(@"Found string '%@'", match);
}
這將輸出:
<a href="text">text</a>
<a href="awesome">awesome</a>
只需搜索<符號,然后搜索下一個>符號,然后刪除該零件。 重復進行,直到沒有跡象為止。 將正則表達式<*>替換為任何內容。
將RegexKitLite框架添加到您的項目。
將標志-licucore
添加到項目設置的Other Linker Flags
中
在您的班級中添加#import "RegexKitLite.h"
然后使用此代碼段消除所有標簽:
NSString *tags = @"<[^>]*>";
NSString *htmlString=@"<html><p>textA</p><p>textB</p></html>";;
NSString *stringWithoutTags = [htmlString stringByReplacingOccurrencesOfRegex:tags withString:@""];
NSLog(@"%@",stringWithoutTags);
//output: textAtextB
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.