【问题标题】:NSString find and replace html tags attgibutesNSString 查找和替换 html 标签 attgibutes
【发布时间】:2013-11-22 11:09:24
【问题描述】:
我有很简单的NSString
f.e
<scirpt attribute_1="x" attribute2="x" attribute3="x" ... attributeX="x"/>
我需要找到具体的参数,比如说attribute2 并替换它的值,
我知道参数 f.e attribute2 的确切名称,但我不知道它的值。
我想这可以通过正则表达式轻松完成,但我是新手。
总结:我要抢
attribute2="xxxx...xxx"
来自传入的字符串
注意:我不想使用一些 3rd 方库来实现这一点(这是临时破解)
感谢任何帮助
【问题讨论】:
标签:
ios
objective-c
regex
nsstring
【解决方案1】:
我把它和一些字符串操作一起破解了:
NSDictionary* valuesToReplace = @{@"attribute_1" : @"newValue1"};
NSString* sourceHtml = @"<scirpt attribute_1=\"x\" attribute2=\"x\" attribute3=\"x\" attributeX=\"x\" />";
NSArray* attributes = [sourceHtml componentsSeparatedByString:@" "];
for (NSString* pair in attributes)
{
NSArray* attributeValue = [pair componentsSeparatedByString:@"="];
if([attributeValue count] > 1) //to skip first "script" element
{
NSString* attr = [attributeValue firstObject]; //get attribute name
if([valuesToReplace objectForKey:attr]) //check if should be replaced
{
NSString* newPair = [NSString stringWithFormat:@"%@=\"%@\"", attr, [valuesToReplace objectForKey:attr]]; //create new string for that attribute
sourceHtml = [sourceHtml stringByReplacingOccurrencesOfString:pair withString:newPair]; //replace it in sourceHtml
}
}
}
真的只有当你想破解它并且你知道格式时:) 如果有任何问题,请提出问题。