NSString匹配字符串开头,如果匹配则替换字符串

时间:2014-04-27 00:05:20

标签: objective-c regex cocoa-touch nsstring

这是我的NSString:

<meta name=3D"viewport" content=3D"width=3Ddevice-width=2C initial=-scale=3D1.0">

我希望字符串以<meta name=3D"viewport开头,以替换<>之间的所有内容(包括<>

例如,如果我有一个字符串:

<meta test>
    <meta name=3D"viewport" content=3D"width=3Ddevice-width=2C initial=-scale=3D1.0">
<meta 2>

处理后,它变为:

  <meta test>
  <meta 2>

1 个答案:

答案 0 :(得分:0)

简而言之:

搜索:<meta name=3D"viewport[^>]*>

替换:""

未经测试的代码:

NSString *string = @"<meta name=3D\"viewport\" content=3D\"width=3Ddevice-width=2C initial=-scale=3D1.0\">";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<meta name=3D\"viewport[^>]*>" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
NSLog(@"%@", modifiedString);