解析URL哈希与正则表达式

问题描述:

需要解析字符串解析URL哈希与正则表达式

#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345 

在哪里我只需要得到oauth_tokenoauth_verifier键+值,什么是正则表达式来做到这一点最简单的方法是什么?

+6

学习正则表达式。 –

+3

随着所有的代表,你应该知道更好地提出一个问题没有代码或努力显示... – Jerry

+0

这是否有助于: - http://*.com/questions/27745/getting-parts-of-a -url-regex ??? –

这将做到这一点,你没有指定你怎么想你的数据输出,所以我分隔用逗号将它们。

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 

这应该工作:

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}