Reputation: 211
I have some html data containing some img tags as follows:
img width=500 height=400
img width=400 height=250
img width=600 height=470
Height and width always changing. I have to replace that html data. I need to replace that html data to "img with=100" using Objective-C.
I wrote these but it's not matching
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"/(img\\s)((width|height)(=)([0-9]+)"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:myhtmldata
options:0
range:NSMakeRange(0, [myhtmldata length])];
NSString *modifiedString;
if (numberOfMatches > 0)
{
modifiedString = [regex stringByReplacingMatchesInString:myhtmldata
options:0
range:NSMakeRange(0, [myhtmldata length])
withTemplate:@"img width=30"];
}
Can you help me ?
Upvotes: 0
Views: 852
Reputation: 211
I found a different method and it's working. Here is code :
NSArray* ary = [oldHtml componentsSeparatedByString:@"<img"];
NSString* newHtml = [ary objectAtIndex:0];
for (int i = 1; i < [ary count]; i++) {
newHtml = [newHtml stringByAppendingString:[@"<img width=300 " stringByAppendingString:[[ary objectAtIndex:i] substringFromIndex:[[ary objectAtIndex:i] rangeOfString:@"src"].location]]];
}
Upvotes: 0
Reputation: 9185
If I infer the intent correctly from your sample code, you just want to use NSRegularExpression
to change the width to 30. Then:
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
@autoreleasepool {
NSError *regexError = nil;
NSRegularExpressionOptions options = 0;
NSString *sampleText = @"img width=500 height=400";
NSString *pattern = @"^(img\\s+)width=\\d+(\\s+height=\\d+)";
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:options error:®exError];
sampleText = [expression stringByReplacingMatchesInString:sampleText
options:0
range:NSMakeRange(0,sampleText.length)
withTemplate:@"$1width=30$2"];
printf("%s\n",[sampleText UTF8String]);
}
}
prints img width=30 height=400
to the console.
EDIT:
You change change the regular expression to (img\s+width=)\d+\s+height=\d+
which when escaped properly will be:
@"(img\\s+width=)\\d+\\s+height=\\d+"
then change the template string to @"$130"
. IF you make those changes to the my original code, you should match all occurrences of the img
tag embedded in HTML. For example, it should change:
<html>
<body>
<img width=500 height=400>
<img width=520 height=100>
</body>
</html>
to:
<html>
<body>
<img width=30>
<img width=30>
</body>
</html>
Is this what your specs call for?
Upvotes: 2