YouTube videoID Matching and replacing - ios

I'm completely stumped on this one, and my complete lack of skill with regular expressions doesn't help.
Here is what I'm trying to achieve:
- I have multiple NSStrings that contain the text (and links) from blog posts that I've downloaded from a site online.
- I'm using a UIWebView with an HTML page I create on the fly so that I can have inline images, videos etc.
- The blog posts contain two types of YouTube link -
<iframe src="//www.youtube.com/embed/VIDEOID" height="405" width="720" allowfullscreen="" frameborder="0"></iframe>
and
http://youtu.be/VIDEOID
There are two different types of URL because the blog uses Wordpress and Wordpress has automatic detection for YouTube links, meaning embeds aren't required. Also the first type of embed doesn't work because it relies on the browser being able to request either http or https (hence the lack of it in the URL there), that apparently doesn't work in UIWebViews.
Essentially what I want to do is find the VideoID from both types of URL, then take the existing URL out of the NSString and replace it with the correct embed type with the correct VideoID attached. I also need to keep the rest of the string intact. To top it all off, it needs to work through multiple URLs in the same NSString, as there are an unknown number of videos per post.
This is the code I have so far, but I know it's horribly wrong and I'm not achieving what I want:
NSString *regexToReplaceRawLinks = #"(https?://)?(www\\.)?(youtu\\.be/|youtube\\.com)?(/|/embed/|/v/|/watch\\?v=|/watch\\?.+&v=)([\\w_-]{11})(&.+)?";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexToReplaceRawLinks
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string
options:0
range:NSMakeRange(0, [string length])
withTemplate:#"<iframe width=\"320\" height=\"180\" src=\"http:\/\/www.youtube.com\/embed\/$1\" frameborder=\"0\" allowfullscreen><\/iframe>"];
NSLog(#"%#", modifiedString);
return modifiedString;
I would be extremely grateful if anyone could point me in the right direction, particularly with the regex's

Assuming // can be the start of your url(as you have shown in your example), you can try this regex:
(?:https?:)?//(?:[^.]*\.)?youtu(?:\.be|be\.com)(?:/|/embed/|/v/|/watch/?\?(?:.+&)?v=)([\w-]{11})
Just escape \ with \\ from above if you need.

Related

ios issue with stringByAddingPercentEscapesUsingEncoding

In my app I need to send some parameters to the url, when I am trying with the stringByAddingPercentEscapesUsingEncoding it is not converting correctly. If I am not using this encoding I am getting null(Exception) from the nsurl.Here is me code.
http://www.mycompurl.co?message=xyz&id=____ here I am sending the id 1 or 2 or any number.
when I convert this string to url by using stringByAddingPercentEscapesUsingEncoding I got
"http://www.mycompurl.co?message=xyz&id=**%E2%80%8B**1" (when I send 1 as parameter). Then I got the 0 data from the Url.
str = [NSString stringWithFormat:#"%#?message=xyz&id=​%#",Application_URL,bootupdateNew];
str = [str stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
url=[NSURL URLWithString:str];
NSError* error = nil;
data1 = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
Thank you In advance
Basics
A URL is composed of several components.
Each component has its own rule how the component's source string must be encoded, so that this component becomes valid within the URL string.
Applying stringByAddingPercentEscapesUsingEncoding: will never always produce a correct URL if the string consists of more than one component (and if we assume, we have an unbounded set of source strings - so that the encoded string actually differs from the source string).
It even won't work always with a string which represents any single component.
In other words, for what's worth, stringByAddingPercentEscapesUsingEncoding: should not be used to try to make a URL out of several components. Even getting the URL query component correctly encoded is at least error prone, and when utilizing stringByAddingPercentEscapesUsingEncoding: it still remains wonky. (You may find correct implementations on SO, though - and I posted one myself).
But now, just forget about it:
It took awhile for Apple to recognize this failure, and invented NSURLComponents. It's available since iOS 7. Take a look! ;)

Extract facebook pages from url [ios]

my problem is very minor but I can't resolve it.
I have 2 facebook url's:
http://www.facebook.com/pages/Name_Of_Page/ID_OF_PAGE
http://www.facebook.com/Name_Of_Page
And I need to extract only the name by using NSRegularExpression.
This is my code:
NSRegularExpression* FBregex = [NSRegularExpression regularExpressionWithPattern:#"((http|https)://)?([w]{3}\\.)?(facebook\\.com/(pages/)?)" options:0 error:&error];
NSString *result=[FBregex stringByReplacingMatchesInString:STRING_TO_EVALUATE options:0 range:NSMakeRange(0, [STRING_TO_EVALUATE length]) withTemplate:#""]
I need to remove the ID of the page to be shown. Any ideas?
thanks.
I've not used NSRegularExpressions before, but if it's Perl-Compatible, there are a couple of ways you can get to what you want.
This is a lookbehind method. Lookbehinds do not capture anything, they just mark a position, so the match starts with the character class and ends when it runs into a word boundary.
~(?<=pages/)[-A-Z0-9_.]+\b~i
This is a Forget Everything method. The \K tells the REGEX engine to require the pages/ to be there, but then forget it. So, it has the same effect of starting the capture at the character class and ending when it runs into a word boundary.
~pages/\K[-A-Z0-9_.]+\b~i
Both of these methods will only give you the name of the page.
Here is a demo

Reference website live updating status from App

I have a website: http://www.grandforks.af.mil/library/weathercenter/index.asp
There is a logo on the middle of the page for the current road conditions on base.
The file names for each condition is different by 1 number.
Green is 19
Yellow is 20
Red is 21
I do not have control over this website.
My question is how can I have the current road conditions in an app that I am building display as a reflection of the website? I don't want to have any user input I want the app to be able to pull off of the site. I have tried using UIWebView but I cannot get it to focus on that area of the page. If I could do that it would probably be the better solution.
Ugly solution:
you can download the html of the website, parse it searching the string "http://www.grandforks.af.mil/shared/media/document/AFD-121002-" and get the actual URL (which is something like http://www.grandforks.af.mil/shared/media/document/AFD-121002-019.jpg).
After that, you can load that URL in your UIImageView or (better) discriminate and show your image that is included in the app.
The ugliness depends by the fact that if they change the image's URL, your app stops working.
I would suggest that when the user opens the app, it goes to check your page and eventually download the string your are looking for. Doing so, if the website changes the url, you can manually modify the source without update the app.
I don't know if using others information is legal.
EDIT:
here is an example that I built that demonstrate how you can substring a string:
NSString *myString = #"11111www.the-site.com/img42.jpg222222222222222";
NSString *searchString = #"www.the-site.com/img";
NSRange range = [myString rangeOfString:searchString];
NSLog(#"searched string strart at character %lu, and it's long %lu charactrers", (unsigned long)range.location, (unsigned long)range.length);
NSInteger index = range.location + range.length;
NSString *mySubString = [myString substringFromIndex:index];
NSLog(#"string from the index: %#", mySubString);
//I know that the substring I'm looking for is long exactly 2 characters
NSString *the_answer = [mySubString substringToIndex:2];
NSLog(#"this should print 42: %#", the_answer);
I added some prints, so you can see step by step what I'm doing.
Obviously you have to change "searchString" with "http://www.grandforks.af.mil/shared/media/document/AFD-121002-" and myString is the html of the page.
I hope it helps.

Efficient way to validate state and zip code

I'm looking for a easy way to validate state and zip code (U.S Only). Obviously there are many ways that this can be done. I have zip code:
- (BOOL)validateZipCode
{
bool returnValue = false;
NSString *zipcodeExpression = #"^[0-9]{5}(-/d{4})?$"; //U.S Zip ONLY!!!
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:zipcodeExpression options:0 error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:ZipCodeTextField.text options:0 range:NSMakeRange(0, [ZipCodeTextField.text length])];
if (match)
{
returnValue = true;
}
return returnValue;
}
Would it be common to just have a list of all the states and abbreviations and just compare the user input to check for a match? This just seems like a lot.
I guess I'm looking for alternatives. I also heard of some frameworks that when a user inputs a zip code, the city and state are then auto generated. Does anyone know of any alternatives like this?
I simple plist file in your app preloaded with the state names and abbreviations is trivial enough. Your regular expression will validate that a string represents a valid zip code.
If you need to actually verify that the zip code and the state match, that will take a lot more data.
A quick google search should reveal some web services you may be able to use to get a state from a zip code. Zip codes change (at least new ones added) on occasion. You may be able to provide a state/zip code database file in your app. But you will need a way to update the database once in a while without needing to submit an update of your app.
Update: A quick look at the Wikipedia Zip Code page reveals that some zip codes span more than one state.

Simple (tutorial/blog/explanation) of basic RegEx implementation(searching for a string in another string) in Cocoa XCode?

I have an html code stored in a string. Now I want to extract one of the images from the source code.
I was earlier using REgExKitLite but according to this link http://www.cocoabuilder.com/archive/cocoa/288966-applications-using-regexkitlite-no-longer-being-accepted-at-the-appstore.html , it's suggested not to use REgExKitLite if we want to submit my app to app store.
I just need a very simple implementation to extract one string from another using regEx. Most of the other SO solutions are trying to achieve pretty complex tasks and hence its difficult to understand for a beginner like me.
Even a good tutorial link(about NSRegularExpression implementation) will do. I really dont mind reading it and learning the basics as long as the tutorial is simple and clear. Thnx!
In iOS 4.0+, you can use NSRegularExpression:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"stack(.*).html" options:0 error:NULL];
NSString *str = #"stackoverflow.html";
NSTextCheckingResult *match = [regex firstMatchInString:str options:0 range:NSMakeRange(0, [str length])];
// [match rangeAtIndex:1] gives the range of the group in parentheses
// [str substringWithRange:[match rangeAtIndex:1]] gives the first captured group in this example
You can follow this reference to get more solutions.

Resources