使用NsRegularExpression搜索和替换

时间:2013-05-23 16:40:19

标签: ios uiwebview nsregularexpression

我将字符串中px中的字体替换为另一个值。之后,我替换了字符串中的px,我将它传递给UIWebView来显示它。问题是在我更改px值后,它没有效果。

字符串包含这样的HTML(例如):

<html><head><script> document.ontouchmove = function(event) { if (document.body.scrollHeight == document.body.clientHeight) event.preventDefault(); } </script><style type='text/css'>* { margin:0; padding:0; } p { color:black; font-family:Helvetica; font-size:26px; } a { color:#000000;}</style></head><body>Look at Google</body></html>

代码如下所示:

//Setting of WebSites Text
NSString *websitesHTML = [[websitesArray objectAtIndex:index] objectForKey:@"Websites"];

//For iPad
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\d\\dpx;" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedWebsitesHTML = [regex stringByReplacingMatchesInString:websitesHTML options:0 range:NSMakeRange(0, [websitesHTML length]) withTemplate:@"40px"];
NSLog(@"%@",modifiedWebsitesHTML);

UIWebView *websitesWebView = [[UIWebView alloc] init];
[websitesWebView setFrame:CGRectMake(15, 160, 600, 300)];
websitesWebView.delegate = self;
[websitesWebView setOpaque:NO];
websitesWebView.backgroundColor = [UIColor clearColor];
[websitesWebView loadHTMLString:modifiedWebsitesHTML baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
[self.view addSubview:websitesWebView];

任何建议都会有所帮助......需要一些指导......

1 个答案:

答案 0 :(得分:2)

看起来您的正则表达式不匹配,因为“26px”后面没有HTML中的分号。将其添加到HTML中或从模式中删除它。

编辑:更改后的CSS没有效果,因为它标注了<p>标记,但<body>不包含。{/ p>