URL Regex Crashed iOS App - iphone

I have URL Regex Method like that;
NSString *urlRegEx = #"(http://|https://|www.)((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*)|([#^?'+!&%.#=*]))+((\\w)*|([0-9]*|([#^?'+!&%.#=*])))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
NSArray *urlArray = [textView.text componentsSeparatedByString:#" "];
It works great but however if URL contains '-' or '_' application crashed. Do you have any idea about problem?

Ok folks i have found solution like that;
NSString *urlRegEx = #"(http://|https://|www.)((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*)|([-_#^?'+!&%.#=*]))+((\\w)*|([0-9]*|([-_#^?'+!&%.#=*])))+";

Related

Get the extension of a file contained in an NSString

I have an NSMutable dictionary that contains file IDs and their filename+extension in the simple form of fileone.doc or filetwo.pdf. I need to determine what type of file it is to correctly display a related icon in my UITableView. Here is what I have done so far.
NSString *docInfo = [NSString stringWithFormat:#"%d", indexPath.row]; //Determine what cell we are formatting
NSString *fileType = [contentFiles objectForKey:docInfo]; //Store the file name in a string
I wrote two regex to determine what type of file I'm looking at, but they never return a positive result. I haven't used regex in iOS programming before, so I'm not entirely sure if I'm doing it right, but I basically copied the code from the Class Description page.
NSError *error = NULL;
NSRegularExpression *regexPDF = [NSRegularExpression regularExpressionWithPattern:#"/^.*\\.pdf$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSRegularExpression *regexDOC = [NSRegularExpression regularExpressionWithPattern:#"/^.*\\.(doc|docx)$/" options:NSRegularExpressionCaseInsensitive error:&error];
NSUInteger numMatch = [regexPDF numberOfMatchesInString:fileType options:0 range:NSMakeRange(0, [fileType length])];
NSLog(#"How many matches were found? %#", numMatch);
My questions would be, is there an easier way to do this? If not, are my regex incorrect? And finally if I have to use this, is it costly in run time? I don't know what the average amount of files a user will have will be.
Thank you.
You're looking for [fileType pathExtension]
NSString Documentation: pathExtension
//NSURL *url = [NSURL URLWithString: fileType];
NSLog(#"extension: %#", [fileType pathExtension]);
Edit you can use pathExtension on NSString
Thanks to David Barry
Try this :
NSString *fileName = #"resume.doc";
NSString *ext = [fileName pathExtension];
Try this, it works for me.
NSString *fileName = #"yourFileName.pdf";
NSString *ext = [fileName pathExtension];
Documentation here for NSString pathExtension
Try using [fileType pathExtension] to get the extension of the file.
In Swift 3 you could use an extension:
extension String {
public func getExtension() -> String? {
let ext = (self as NSString).pathExtension
if ext.isEmpty {
return nil
}
return ext
}
}

Parse NSString from right hand side?

> (2009 RX7)</font></td>
>monospace" size="-1">214869 (2007 PAZ)</font></td>
>monospace" size="-1"> 4155 Accord</font></td>
I wonder if someone could offer me a little help, I have a list of NSString items (See Above) that I want to parse some data from. My problem is that there are no tags that I can use within the strings nor do the items I want have fixed positions. The data I want to extract is:
2009 RX7
2007 PAZ
4155 Accord
My thinking is that its going to be easier to parse from the right hand end, remove the </font></td> and then use ";" to separate the data items:
(2009&nbsp RX7)
(2007&nbsp PAZ)
4155&nbsp Accord
which can them be cleaned up to match the example given. Any pointers on doing this or working through from the right would be very much appreciated.
Personally I think you are better off with a regex. So my solution would be:
Regex of: ([0-9]+)[^;]+;([A-Za-z0-9]+)
Which for all the example text provides 3 matches. ie for:
(2009 RX7)</font></td>
0: 2009 RX7)<
1: 2009
2: RX7
I haven't coded this up, but did test the Regex at www.regextester.com
Regex's are implemented via NSRegularExpression and are available in iOS 4.0 and later.
Edit
Given that this appears to be a web scraping application, you never know when those pesky HTML code monkeys will change their output and break your carefully crafted matching methodology. As such I would change my regex to:
([0-9]+)([^;]+;)+([A-Za-z0-9]+)
Which adds an extra group, but allows for any number of elements between the number and the string.
Try this code:
NSString *str = #"> (2009 RX7)</font></td>";
NSRange fontRange = [str rangeOfString:#"</Font>" options:NSBackwardsSearch];
NSRange lastSemi = [str rangeOfString:#";" options:NSBackwardsSearch range:NSMakeRange(0, fontRange.location-1)];
NSRange priorSemi = [str rangeOfString:#";" options:NSBackwardsSearch range:NSMakeRange(0, lastSemi.location-1)];
NSString *yourString = [str substringWithRange:NSMakeRange(priorSemi.location+1, fontRange.location-1)];
The key element here is the NSBackwardsSearch search option.
This should do the trick:
NSString *s = #">monospace\" size=\"-1\"> 4155 Accord</font></td>";
NSArray *strArray = [s componentsSeparatedByString:#";"];
// you're interested in last two objects
NSArray *tmp = [strArray subarrayWithRange:NSMakeRange(strArray.count - 2, 2)];
In tmp you'll have something like:
"4155&nbsp",
"Accord</font></td>"
strip unneeded chars and you're all set.
Using NSRegularExpression:
NSRegularExpression *regex;
NSTextCheckingResult *match;
NSString *pattern = #"([0-9]+) ([A-Za-z0-9]+)[)]?</font></td>";
NSString *string = #"> (2009 RX7)</font></td>";
regex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regex firstMatchInString:string options:0 range:NSMakeRange(0, [string length])];
NSLog(#"'%#'", [string substringWithRange:[match rangeAtIndex:1]]);
NSLog(#"'%#'", [string substringWithRange:[match rangeAtIndex:2]]);
NSLog output:
'2009'
'RX7'

How to get find and get URL in a NSString in iPhone?

I have a text with http:// in NSString. I want to get that http link from the NSString. How can i get the link/url from the string? Eg: 'Stack over flow is very useful link for the beginners https://stackoverflow.com/'. I want to get the 'https://stackoverflow.com/' from the text. How can i do this? Thanks in advance.
I am not sure what you exactly mean by link but if you want to convert your NSString to NSURL than you can do the following:
NSString *urlString = #"http://somepage.com";
NSURL *url = [NSURL URLWithString:urlString];
EDIT
This is how to get all URLs in a given NSString:
NSString *str = #"This is a grate website http://xxx.xxx/xxx you must check it out";
NSArray *arrString = [str componentsSeparatedByString:#" "];
for(int i=0; i<arrString.count;i++){
if([[arrString objectAtIndex:i] rangeOfString:#"http://"].location != NSNotFound)
NSLog(#"%#", [arrString objectAtIndex:i]);
}
Rather than splitting the string into an array and messing about that way, you can just search for the substring beginning with #"http://":
NSString *str = #"Stack over flow is very useful link for the beginners http://stackoverflow.com/";
// get the range of the substring starting with #"http://"
NSRange rng = [str rangeOfString:#"http://" options:NSCaseInsensitiveSearch];
// Set up the NSURL variable to hold the created URL
NSURL *newURL = nil;
// Make sure that we actually have found the substring
if (rng.location == NSNotFound) {
NSLog(#"URL not found");
// newURL is initialised to nil already so nothing more to do.
} else {
// Get the substring from the start of the found substring to the end.
NSString *urlString = [str substringFromIndex:rng.location];
// Turn the string into an URL and put it into the declared variable
newURL = [NSURL URLWithString:urlString];
}
try this :
nsstring *str = #"Stack over flow is very useful link for the beginners http://stackoverflow.com/";
nsstring *http = #"http";
nsarray *arrURL = [str componentsSeparatedByString:#"http"];
this will give two objects in the nsarray. 1st object will be having:Stack over flow is very useful link for the beginners and 2nd will be : ://stackoverflow.com/ (i guess)
then you can do like:
NSString *u = [arrURL lastObject];
then do like:
nsstring *http = [http stringByAppendingFormat:#"%#",u];
Quite a lengthy,but i think that would work for you. Hope that helps you.

Evaluate/compare NSString with wildcards?

Hi
I'm trying to evaluate an NSString to see if it fits a certain criteria, which contains wildcards in the form of one or more asterix characters.
Example:
NSString *filePath = #"file://Users/test/Desktop/file.txt";
NSString *matchCriteria = #"file://*/file.*";
I would like to see if filePath matches (fits?) matchCriteria, in this example it does.
Does anybody know how I can go about doing this?
Many thanks!
In addition to NSRegularExpression, you can also use NSPredicate.
NSString *filePath = #"file://Users/test/Desktop/file.txt";
NSString *matchCriteria = #"file://*/file.*";
NSPredicate *pred = [NSPredicate predicateWithFormat:#"self LIKE %#", matchCriteria];
BOOL filePathMatches = [pred evaluateWithObject:filePath];
The Predicate Programming Guide is a comprehensive document desribing how predicates work. They can be particularly useful if you have an array of items that you want to filter based on some criteria.
NSString implements these methods:
#interface NSObject (NSComparisonMethods)
- (BOOL)isLike:(NSString *)object;
- (BOOL)isCaseInsensitiveLike:(NSString *)object;
#end
They are much faster than NSPredicate and NSRegularExpression.
You can use NSRegularExpression.

Swear Filter in Objective-C: Needed for iPhone App

Need to filter our swear words that are inputted to the iPhone app and inserted to our database. I'd like to catch this before passing to our database.
Currently, I was using:
stringByReplacingOccurrencesOfString:#"swear" withString:#""
but this seems inefficient to list 20+ words that need to be filtered. What's the best way to approach this?
Here is my complete code
NSUserDefaults *p = [NSUserDefaults standardUserDefaults];
NSString* string1 = [[p valueForKey:#"user"] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString* string2 = [[p valueForKey:#"pass"] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString* string3 = [[[[[[[[[[[[[[tvA.text stringByReplacingOccurrencesOfString:#"\n" withString:#" "] stringByReplacingOccurrencesOfString:#"&" withString:#"and"] stringByReplacingOccurrencesOfString:#"ç" withString:#"c"] stringByReplacingOccurrencesOfString:#"+" withString:#"plus"] stringByReplacingOccurrencesOfString:#"swear" withString:#""] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString* urlString = [NSString stringWithFormat:#"http://domain.com/qa.php?user=%#&pass=%#&id=%#&body=%#",string1,string2,[p valueForKey:#"a"],string3];
id val1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
To do it the way you're doing it, it would be much more sensible to keep a list of filtered strings and their replacements — you could even use an external plist file. Then you could either loop through the list, replacing as you go, or create an NSRegularExpression if you're looking for more sophisticated filtering.