簡體   English   中英

通過NSRegularExpression獲取Javascript函數之間的特定值?

[英]Get specific Value between Javascript Function by NSRegularExpression?

我正在創建一個用於學習目的的項目:

FOR INFO:我沒有使用過UIWebView

在我的項目中,我從服務器獲取HTML數據( 內容 )。 該數據包含有關地點的所有信息( 來自google map )。 為了從HTML內容獲取特定數據,我需要解析HTML 我使用Hpple解析HTML 而且我可以成功解析HTML以獲取特定數據( 例如名稱,地址等 ),但是當我需要HTML內容解析緯度和經度時 ,我對於如何獲取地點的緯度和經度感到困惑,因為這些是其中一部分Javascript 我的意思是這些緯度和經度數據在Javascript's函數中可用。

我從Server獲得的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://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]
           }
}

在上面的代碼中,我想從latlng:{lat:21.747064,lng:72.169678}獲取lat:lon:

為了從javascript獲取它, 我在Google上搜索了一下,發現我需要使用NSRegularExpression類來獲取特定的NSRegularExpressionData )表單內容。

然后我嘗試了以下代碼

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獲取搜索節點的內容?

如果您確實要使用正則表達式,則以下模式應適用:

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

[0-9.]+匹配一個或多個數字或. ,並用括號括起來成為“捕獲組”,以便可以使用rangeAtIndex:獲得與模式的這一部分匹配的字符串部分。

為了驗證這一點,我將您問題中的確切輸入數據作為資源文件“ data.txt”添加到了我的測試應用程序中,並使用

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

然后用正則表達式解析字符串

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引擎為您輕松進行JSON解析的能力。 替換Javascript函數中的return以匹配您的數據結構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM