正则表达式在Java中获取AccessToken

时间:2015-04-30 16:10:30

标签: java regex

我需要通过正则表达式从下面的字符串获取访问令牌:

=的access_token的 CAABletmsJHgBAEMfdJEgA1wEXgqwVgfM1nrTgyHq9XxkIEvLVGOUMq80ZBaA2ZA6Ndc18xNwZAJCDwpILNSKgGiVu4SIm9Bas5ocv7ZCVFV1bxKrNW9qrIqK1HKIz3uD6nO4RQnVgfVmLggoqZCVkPwjEY79ijZC0SYKPYM2RN9qg4TZB5E2iMz5WfAAACddAbXaEZCbzkBSoSZBTlEyea8rC &安培;期满= 5181509

我想要一个模式匹配提供的字符串中 expires access_token 的随意位置。

我是正则表达式的新手,我的模式效果不佳

access_token=(.*?)&expires=\d+

请帮帮我吗?

https://regex101.com/r/oS4xE5/1

2 个答案:

答案 0 :(得分:2)

你可以使用" lookarounds"以下成语:

String input = "access_token=CAABletmsJHgBAEMfdJEgA1wEXgqwVgfM1nr" +
    "TgyHq9XxkIEvLVGOUMq80ZBaA2ZA6Ndc18xNwZAJCDwpILNSKgGiVu4SIm9B" +
    "as5ocv7ZCVFV1bxKrNW9qrIqK1HKIz3uD6nO4RQnVgfVmLggoqZCVkPwjEY79" +
    "ijZC0SYKPYM2RN9qg4TZB5E2iMz5WfAAACddAbXaEZCbzkBSoSZBTlEyea8rC" +
    "&expires=5181509";
//                           ┌ preceded by "access_token"
//                           |                 ┌ anything reluctantly quantified 
//                           |                 |  ┌ followed by "&"
Pattern p = Pattern.compile("(?<=access_token=).+?(?=&)");
Matcher m = p.matcher(input);
if (m.find()) {
    System.out.println(m.group());
}

<强>输出

CAABletmsJHgBAEMfdJEgA1wEXgqwVgfM1nrTgyHq9XxkIEvLVGOUMq80ZBaA2ZA6Ndc18xNwZAJCDwpILNSKgGiVu4SIm9Bas5ocv7ZCVFV1bxKrNW9qrIqK1HKIz3uD6nO4RQnVgfVmLggoqZCVkPwjEY79ijZC0SYKPYM2RN9qg4TZB5E2iMz5WfAAACddAbXaEZCbzkBSoSZBTlEyea8rC

注意

这将验证少于您与当前模式匹配的内容,因为它仅提取access_token=&之间的内容。

答案 1 :(得分:0)

我不明白为什么这个正则表达式不能与那个正则表达式分开来解决这个问题。&#39; \&#39;必须在Java中进行转义,如下:

     Pattern p = Pattern.compile("access_token=(.*?)&expires=\\d+");
     Matcher m = p.matcher("access_token=CAABletmsJHgBAEMfdJEgA1wEXgqwVgfM1nrTgyHq9XxkIEvLVGOUMq80ZBaA2ZA6Ndc18xNwZAJCDwpILNSKgGiVu4SIm9Bas5ocv7ZCVFV1bxKrNW9qrIqK1HKIz3uD6nO4RQnVgfVmLggoqZCVkPwjEY79ijZC0SYKPYM2RN9qg4TZB5E2iMz5WfAAACddAbXaEZCbzkBSoSZBTlEyea8rC&expires=5181509");
     if (m.find()) {
         System.out.println(m.group(1));
    }

<强>输出

  

CAABletmsJHgBAEMfdJEgA1wEXgqwVgfM1nrTgyHq9XxkIEvLVGOUMq80ZBaA2ZA6Ndc18xNwZAJCDwpILNSKgGiVu4SIm9Bas5ocv7ZCVFV1bxKrNW9qrIqK1HKIz3uD6nO4RQnVgfVmLggoqZCVkPwjEY79ijZC0SYKPYM2RN9qg4TZB5E2iMz5WfAAACddAbXaEZCbzkBSoSZBTlEyea8rC