NSRegularExpression class in Xamarin - ios

Can any one suggest me how to use NSRegularExpression class in Xamarin iOS.
I am not able to use this in Xamarin Studio,
Looking for an equivalent method for the below one
NSArray* matches = [[NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionDotMatchesLineSeparators error:nil] matchesInString:string options:0 range:range];

You can use the Regex.Matches(String,String,RegexOptions)
Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options.
NSRegularExpressionDotMatchesLineSeparators is the same as an inline option (?s) that you can add to the beginning of your pattern, or use a RegexOptions.Singleline flag with Regex.Matches.

Related

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

YouTube videoID Matching and replacing

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.

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.

Special characters in XML attributes with NSXMLParser

I get something like the following from a third party API:
<el attr="test.
another test." />
I use NSXMLParser to read the file into my app.
However, in the delegate, the attribute gets converted to test. another test. Obviously I'd like to see it with the line breaks intact.
I initially assumed that this was a bug but, according to the XML Spec it's doing the right thing:
a whitespace character (#x20, #xD, #xA, #x9) is processed by
appending #x20 to the normalized value
(See section 3.3.3.)
What are my options? Note that it's a third party API so I can't change it, even though it's wrong.
NSData *xmlData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"url://"]];
NSMutableString *myXmlStr = [[NSMutableString alloc] initWithData:xmlData encoding:NSUTF8StringEncoding];
NSRange range = [myXmlStr rangeOfString:#"\n"];
[myXmlStr replaceCharactersInRange:range withString:#"[:newline:]"];
NSData *newXmlData = [myXmlStr dataUsingEncoding:NSUTF8StringEncoding];
Just replace [:newline:] with new line character whenever u like it :)

Resources