I am creating a project for learning purpose:
FOR INFO : I have not used UIWebView
In my project I got HTML data(content) from server. This data contains all information about places(from google map). For getting specific data from HTML content I need to parse HTML. I parse HTML using Hpple. And I could successfully parse HTML to get specific data (Such as name,address…etc), but when I need to parse latitude and longitude from HTML content, I am confused about how to get latitude and longitude of places, because those are part of Javascript. I mean these latitude and longitude data are available in Javascript's functions.
Javascript content that I got from Server: (My limitation is that, I can only put piece of javascript code bacause this code is very very long)
function()
{
window.gHomeVPage=
{
title:'Hostel, Bhavnagar, Gujarat, India - Google Maps',url:'/?q\\x3dHostel,+Bhavnagar,+Gujarat,+India\\x26hq\\x3dHostel,\\x26hnear\\x3dBhavnagar,+Gujarat,+India\\x26t\\x3dm\\x26ie\\x3dUTF8',urlViewport:false,ei:'jp8tUb3uNK2ciAeQroGACw',
form:{
selected:'q',
q:{q:'Hostel, Bhavnagar, Gujarat, India',what:'Hostel,',near:'Bhavnagar, Gujarat, India'},d:{saddr:'',daddr:'',dfaddr:'Bhavnagar, Gujarat, India'},geocode:''},
query:{type:'l'},viewport:{center:{lat:21.757528,lng:72.15303},span:{lat:0.034314,lng:0.039956},zoom:14,mapType:'m',source:0},modules:['','strr','pphover','act_s','appiw','rst'],
overlays:{sxcar:false,
markers:
[{id:'A',cid:'7569356420090555589',latlng:{lat:21.747064,lng:72.169678},image:'http://maps.gstatic.com/intl/en_ALL/mapfiles/markers2/circleA.png',sprite:{width:20,height:34,top:0,image:'http://maps.gstatic.com/mapfiles/markers2/red_circle_markers_A_J2.png'},icon_id:'A',ext:{width:20,height:34,shadow:'http://maps.gstatic.com/intl/en_ALL/mapfiles/circle-shadow45.png',shadow_width:37,shadow_height:34,mask:false},drg:true,laddr:'Shree Sahajanand Girls Ptc Hostel, Ghogha Road, Bhavnagar, Gujarat 364001, India',geocode:'CfYWJFjKQj0mFXjVSwEdzjhNBCmN5-3pPlpfOTHF7NFVj8ELaQ',sxti:'Shree Sahajanand Girls Ptc Hostel',name:'Shree Sahajanand Girls Ptc Hostel',infoWindow:{title:'Shree Sahajanand Girls Ptc \\x3cb\\x3eHostel\\x3c/b\\x3e',addressLines:['Ghogha Road','Bhavnagar, Gujarat 364001, India'],phones:[{number:'0278 2562529'}],basics:'\\x3cdiv transclude\\x3d\\x22iw\\x22\\x3e\\x3c/div\\x3e',moreInfo:'more info',place_url:'http://maps.google.com/local_url?dq\\x3dHostel,+Bhavnagar,+Gujarat,+India\\x26q\\x3dhttps://plus.google.com/106028699675431268945/about%3Fhl%3Den\\x26s\\x3dANYYN7mCKtIBT1JPxwi6G2b9gVDdCuVyyA',zrvOk:true,loginUrl:'https://www.google.com/accounts/ServiceLogin?service\\x3dlocal\\x26hl\\x3den\\x26nui\\x3d1\\x26continue\\x3dhttp://maps.google.com/maps/place%3Fcid%3D7569356420090555589%26q%3DHostel,%2BBhavnagar,%2BGujarat,%2BIndia%26t%3Dm%26cd%3D1%26cad%3Dsrc:ppwrev%26ei%3Djp8tUb3uNK2ciAeQroGACw%26action%3Dopenratings',lbcurl:'http://www.google.com/local/add/choice?hl\\x3den\\x26gl\\x3dIN\\x26latlng\\x3d7569356420090555589\\x26q\\x3dHostel,\\x26near\\x3dBhavnagar,+Gujarat,+India',link_jsaction:''},ss:{edit:true,detailseditable:true,deleted:false,rapenabled:true,mmenabled:true},b_s:2,approx:true,elms:[4,1,6,2,12,1,9,1,5,2,11]
}
}
Here in above code I want to get value of lat: and lon: from latlng:{lat:21.747064,lng:72.169678}
For getting it from javascript, I googled and found that I need to use NSRegularExpression class for get specific matches(of Data) form content.
Then I tried with following code
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(?-imsx:latlng:)" options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *arrayOfAllMatches = [regex matchesInString:locationStr options:0 range:NSMakeRange(0, [locationStr length])];
for (NSTextCheckingResult *match in arrayOfAllMatches)
{
NSString* substringForMatch = [locationStr substringWithRange:match.range];
NSLog(#"%#",substringForMatch);
}
I got output in console like this:
2013-02-28 11:35:25.051 MapExample[949:13d03] latlng:
2013-02-28 11:35:25.766 MapExample[949:13d03] latlng:
2013-02-28 11:35:26.208 MapExample[949:13d03] latlng:
2013-02-28 11:35:26.799 MapExample[949:13d03] latlng:
2013-02-28 11:35:27.303 MapExample[949:13d03] latlng:
2013-02-28 11:35:27.722 MapExample[949:13d03] latlng:
How can I get content of searched node from NSRegularExpression ?
If you really want to use a regular expression, this following pattern should work:
NSString *pattern = #"latlng:\\{lat:([0-9.]+),lng:([0-9.]+)\\}";
[0-9.]+ matches one or more characters which are a digit or ., and the parentheses around it make it a "capture group", so that the part of the string that matches this part of the pattern is available using rangeAtIndex:.
To verify this, I have added the exact input data from your question as a resource file "data.txt" to my test application, and loaded that data with
NSURL *url = [[NSBundle mainBundle] URLForResource:#"data.txt" withExtension:nil];
NSError *error;
NSString *locationStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
and then parsed the string with the regular expression
NSString *pattern = #"latlng:\\{lat:([0-9.]+),lng:([0-9.]+)\\}";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];
NSArray *matches = [regex matchesInString:locationStr options:0 range:NSMakeRange(0, [locationStr length])];
for (NSTextCheckingResult *match in matches)
{
NSString *lat = [locationStr substringWithRange:[match rangeAtIndex:1]];
NSString *lng = [locationStr substringWithRange:[match rangeAtIndex:2]];
NSLog(#"latidude = %#, longitude = %#", lat, lng);
}
Output:
latidude = 21.747064, longitude = 72.169678
While not a direct answer to your question, there's actually an easier way to do this, using UIWebView:
+(NSString *)valueFromJSON:(NSString *)json andKey:(NSString *)key {
UIWebView webView = [[UIWebView alloc] init];
return [webView stringByEvaluatingJavaScriptFromString:[NSString withFormat:#"(function(){ var v = %#; return var.%#; }())", json, key]];
}
I'll apologize in advance for any syntax errors I've invariably made due to not being on my Mac and it being rather late. If you call this code repeatedly, it might be wise not to initialize a new WebView every time. This exploits the ability of WebKit's Javascript engine to do easy JSON parsing for you. Replace the return in the Javascript function to match your data structure.
I am working on regular expressions but where ever I search I am getting the code and explanation for validating the email now I have to do something like this
Contents of the file are like this(file formate may be .rtf, .txt ...etc)
[Title:languageC]
[Author:Dennis Ritchie]
[Description:this book is nice to learn the C language]
form this file now I want to extract the languageC, Dennis Ritchie, this book is nice to learn the C language. I have achieved this by using NSStrings, NSScanner and NSRange but now I want to achieve this same using regularexpressions is it possible.
NSString *regexStr = #"\[Title:([.]+)\][ ]+\[Author:([.]+)\][ ]+\[Description:([.]+)\]";
NSError *error;
NSRegularExpression *testRegex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error];
if( testRegex == nil ) NSLog( #"Error making regex: %#", error );
NSTextCheckingResult *result = [testRegex firstMatchInString:test options:0 range:NSMakeRange(0, [test length])];
NSRange range = [result rangeAtIndex:1]; // This will give you Title,
You should use a regex like this:
/\[[^:]+:([^]])\]/
E.g.:
NSError *error;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\[[^:]+:([^]])\]" options:0 error:&error];
NSArray* matches = [regex matchesInString:YOUR_STR options:0 range:NSMakeRange(0, [YOUR_STRING length]);
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
}
}
If I had the following:
NSString *tweet = #"Shoutout to #somebody and #somebodyElse for your help on this one #shoutouts";
How would i go about finding the range of the twitter handles (eg #somebody)??
I want to make them bold in my Attributed String which is the next step.
Bonus points if you can help me find the # hash tags as well, but I assume its the same algorithm.
NSRegularExpression is your friend.
Use NSRegularExpression class,
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSRegularExpression_Class/Reference/Reference.html
Than trying using this online tool to build Regex,
http://www.gskinner.com/RegExr/
I tried this and it seems like you can build a good one,
SAMPLE CODE - NOT TESTED
NSString *yourString = #"Shoutout to #somebody and #somebodyElse for your help on this one #shoutouts";
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"\#\S+|#\S+"
options:NSRegularExpressionCaseInsensitive
error:&error];
[regex enumerateMatchesInString:yourString options:0 range:NSMakeRange(0, [yourString length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){
// your code to handle matches here
}];
About test in online tool!
Good luck!
example: word with number in string
NSString *str = [NSString stringWithFormat:#"this is an 101 example1 string"]
Since example1 has a number in the end and i want to remove it. I can break it into an array and filter it out using predicate, but that seems slow to me since I need to do like a million of these.
What would be a more efficient way?
Thanks!
Probably NSRegularExpression. I think ([^0-9 ]+)\d+|\d+([^0-9 ]+) should do it. Just replace it with $1.
Based on Chuck's response, here is the complete code in case someone might find it useful:
NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"([^0-9 ]+)\\d+|\\d+([^0-9 ]+)"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:str2
options:0
range:NSMakeRange(0, [str2 length])
withTemplate:#"$1"];