2013-08-18 24 views
0

需要解析字符串解析URL哈希與正則表達式

#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345 

在哪裏我只需要得到oauth_tokenoauth_verifier鍵+值,什麼是正則表達式來做到這一點最簡單的方法是什麼?

+6

學習正則表達式。 –

+3

隨着所有的代表,你應該知道更好地提出一個問題沒有代碼或努力顯示... – Jerry

+0

這是否有助於: - http://stackoverflow.com/questions/27745/getting-parts-of-a -url-regex ??? –

回答

2

這將做到這一點,你沒有指定你怎麼想你的數據輸出,所以我分隔用逗號將它們。

import java.util.regex.*; 

class rTest { 
    public static void main (String[] args) { 
    String in = "#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345"; 
    Pattern p = Pattern.compile("(?:&([^=]*)=([^&]*))"); 
    Matcher m = p.matcher(in); 
    while (m.find()) { 
     System.out.println(m.group(1) + ", " + m.group(2)); 
    } 
    } 
} 

正則表達式:

(?:   group, but do not capture: 
    &   match '&' 
    (   group and capture to \1: 
    [^=]*  any character except: '=' (0 or more times) 
    )   end of \1 
    =   match '=' 
    (   group and capture to \2: 
    [^&]*  any character except: '&' (0 or more times) 
    )   end of \2 
)    end of grouping 

輸出:

oauth_token, theOAUTHtoken 
oauth_verifier, 12345 
0

這應該工作:

String s = "#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345"; 
Pattern p = Pattern.compile("&([^=]+)=([^&]+)"); 
Matcher m = p.matcher(s.substring(1)); 
Map<String, String> matches = new HashMap<String, String>(); 
while (m.find()) { 
    matches.put(m.group(1), m.group(2)); 
} 
System.out.println("Matches => " + matches); 

OUTPUT:

Matches => {oauth_token=theOAUTHtoken, oauth_verifier=12345}