stringByReplacingMatchesInString: returns (null) - iphone

Here is my code:
NSRegularExpression * regex;
- (void)viewDidLoad {
NSError *error = NULL;
regex = [NSRegularExpression regularExpressionWithPattern:#"<*>" options:NSRegularExpressionCaseInsensitive error:&error];
}
- (IBAction)findWord {
NSString * fileContents=[NSString stringWithContentsOfFile:[NSString stringWithFormat:#"%#/report1_index1_page1.html", [[NSBundle mainBundle] resourcePath]]];
NSLog(#"%#",fileContents);
NSString * modifiedString = [regex stringByReplacingMatchesInString:fileContents
options:0
range:NSMakeRange(0, [fileContents length])
withTemplate:#"$1"];
NSLog(#"%#",modifiedString);
}
My 'modifiedString' is returning (null).Why?I want to replace any characters between '<' and '>' including '<' and '>' simply by a space.

I am guessing this has a lot to do with the fact that you are assigning an autoreleased object to regex in viewDidLoad. Try adding a retain or move the line to the findWord method.
Regex
The regular expression for matching everything between < and > is incorrect. The correct way would be,
NSError *error = nil;
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:#"(?<=<).*(?=>)" options:NSRegularExpressionCaseInsensitive error:&error];
if ( error ) {
NSLog(#"%#", error);
}
Replace by space
If you want to replace the matched string with " " then you shouldn't pass $1 as the template. Rather, use " " as the template.
NSString * modifiedString = [regex stringByReplacingMatchesInString:fileContents
options:0
range:NSMakeRange(0, [fileContents length])
withTemplate:#" "];

Related

finding the index/position of a character in the URL format

I have the following url:
http://test.me/s/hq6aN
I basically wanted to replace that s with an d, what is the best way to do this using NSRegularExpression easily? Essentially what I want is to figure out the index of the /s/ in a string any idea how?
Here's what I have so far:
NSString *regexStr = #"/s/";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error];
NSArray *matches = [regex matchesInString:shortLink options:0 range:NSMakeRange(0, [shortLink length])];
if ([matches count] > 0){
NSTextCheckingResult *matchesIndex = [matches objectAtIndex:0];
NSRange range = matchesIndex.range;
}
I am pretty sure I am doing something wrong with the regexStr
Your pattern looks fine, but there's a convenience method for doing search-and-replace that allows you to write this much more succinctly:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"/s/" options:0 error:&error];
NSMutableString *haystack = [NSMutableString stringWithString:#"http://test.me/s/hq6aN"];
[regex replaceMatchesInString:haystack options:0 range:NSMakeRange(0, [haystack length]) withTemplate:#"/d/"];
There is an equivalent -stringByReplacingMatchesInString:options:range:withTemplate: for NSStrings if you'd prefer to keep the string containing the original URL immutable.

NSRegularExpression searching for unknown value

So I am working on an iPhone app, and it takes a picture of some text, the picture gets OCR'ed and sent back to me, and I then I use a regular expression to search the string for double values up to xxxx.xx.
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\\d?\\d?\\d?\\d?\\.\\d?\\d?"
options:0
error:&error];
NSRange range = [regex rangeOfFirstMatchInString:result
options:0
range:NSMakeRange(0, [result length])];
if([result length] > 0)
{
NSString *subString = [result substringWithRange:range];
double r = [subString doubleValue];
Right now it is working as I want, but it only gets the first number it comes to. There could be an indeterminate number of doubles, and I need to get the largest one. What would be the best way to go about that?
Use matchesInString:options:range: instead of rangeOfFirstMatchInString. This will give you an array of NSTextCheckingResult objects, from which you can extract the range.
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\\d?\\d?\\d?\\d?\\.\\d?\\d?"
options:0
error:&error];
NSArray *arr = [regex matchesInString:string options:NSMatchingReportCompletion range:NSMakeRange(0,string.length)];
for (NSTextCheckingResult *obj in arr) {
double r = [[string substringWithRange:obj.range] doubleValue];
NSLog(#"%f",r);
}

Change html tag in NSString

For example I have html string:
<p>
<img mce_src="http://example.com/apple.png" src="http://example.com/apple.png" width="512" height="512" style="">
<br mce_bogus="1">
</p>
How can I change this properties: width="512" height="512"to for example: width="123" height="123"?
Thanks
You could use
- (NSString *)stringByReplacingOccurrencesOfString:(NSString *)target
withString:(NSString *)replacement
Your example with the html in htmlString
htmlString = [htmlString stringByReplacingOccurrencesOfString:#"width=\"512\""
withString:#"width=\"123\""];
EDIT:
Using regex replacement (not tested):
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(.*width=\").*?(\".*?height=\").*?(\".*)"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:htmlString
options:0
range:NSMakeRange(0, [htmlString length])
withTemplate:#"$1<insert width here>$2<insert height here>$3"];
reference:
NSRegularExpression
You should go with regular expressions and try the RegexKitLite library.
NSString *regex = #"(=\"[0-9]+\")";
NSString *replaced = [htmlString stringByReplacingOccurrencesOfRegex:regex usingBlock:^NSString *(NSInteger captureCount, NSString * const capturedStrings[captureCount], const NSRange capturedRanges[captureCount], volatile BOOL * const stop) {
return(#"123");
}];
just take your html in string and Make a function using for loop and on the occurrence of width and height count its length and location and then replace this with new data......i did this...
add new width and height property inside of img tag
NSError *regexError = nil;
NSRegularExpressionOptions options = 0;
NSString *pattern = #"(img)";
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:options error:&regexError];
wihoutWidth = [expression stringByReplacingMatchesInString:wihoutWidth
options:0
range:NSMakeRange(0,wihoutWidth.length)
withTemplate:#"$1 width=293 height=150"];
return wihoutWidth;
How to just replace the width using this code ? And also I want to insert a string or a number in $1
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(.width=\").?(\".?height=\").?(\".*)"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:htmlString
options:0
range:NSMakeRange(0, [htmlString length])
withTemplate:#"$1$2$3"];

Delete each occurence of tag <a> in NSString ios

I have a little problem with regex in iOS.
I want to delete each tag <a> in NSString.
I made this code but it doesn't stop at first occurence of .
NSString *regexStr = #"<a (.+)>(.+)</a>";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:NULL];
prodDescritpion = [regex stringByReplacingMatchesInString:prodDescritpion options:0 range:NSMakeRange(0, [prodDescritpion length]) withTemplate:#"$2"];
Thanks you !
I have find a solution
NSString *regexStr = #"<a ([^>]+)>([^>]+)</a>";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:NULL];
prodDescritpion = [regex stringByReplacingMatchesInString:prodDescritpion options:0 range:NSMakeRange(0, [prodDescritpion length]) withTemplate:#"$2"];
It works fine !
the + operator is greedy, that means it stops at the last occurrence it finds. One solution could also be to use it in the non greedy version (ie it stops at the first occurrence)
NSString *regexStr = #"<a.+?>.+?</a>";

regular expressions iphone

How can I chceck on iPhone with regularexpressions NSStrring contain only this chars: a-zA-Z numbers 0-9 or specialchars: !##$%^&*()_+-={}[]:"|;'\<>?,./
NSCharacterSet *charactersToRemove = [[NSCharacterSet characterSetWithCharactersInString:#"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 "] invertedSet];
NSString *stringValueOfTextField = [[searchBar.text componentsSeparatedByCharactersInSet:charactersToRemove]
componentsJoinedByString:#""];
try this::::
For this purposes you can use standard class NSRegularExpression
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\w[!##$%^&*()_+-={}\[\]:\"|;'\<>?,./]"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:string
options:0
range:NSMakeRange(0, [string length])];
Note that NSRegularExpression is only available on iOS 4 and above.