Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 用正则表达式解析URL哈希_Java_Regex - Fatal编程技术网

Java 用正则表达式解析URL哈希

Java 用正则表达式解析URL哈希,java,regex,Java,Regex,需要解析这个字符串 #Login&oauth_token=theOAUTHtoken&oauth_verifier=12345 如果我只需要获取oauth_令牌和oauth_验证器key+值,那么使用正则表达式执行此操作的最简单方法是什么?这应该可以: String s = "#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345"; Pattern p = Pattern.compile("&([^=

需要解析这个字符串

#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345
如果我只需要获取
oauth_令牌
oauth_验证器
key+值,那么使用正则表达式执行此操作的最简单方法是什么?

这应该可以:

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

这样就可以了,您没有指定数据输出的方式,所以我用逗号将它们分开

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

学习正则表达式。有了所有的代表,你应该知道不要在没有代码或努力的情况下问问题……这有帮助吗:-???
oauth_token, theOAUTHtoken
oauth_verifier, 12345