TestRaptor
TestRaptor

Reputation: 1315

How to use regex to grab a substring

I have the following string

{  "access_token": "1234-1234-1234-1234-1234",  "expires_in": 9998,  "refresh_token": "abc-abc-abc-1234",  "token_type": "test"}

I only want to grab the access_token value (1234-1234-1234-1234-1234). I have tried creating a substring like this, and it worked

String s2 = result.substring(20,57);

The problem I am having is that "access_token" will not always be listed first in the string, and the value will not always be the same length. Is there a way I can make sure this value is always grabbed using regex?

I haven't used regular expressions much, so here is where I am stuck. I tried the below, but it selects too much.

(?i)"access_token":\s\S(.*)",

Upvotes: 2

Views: 110

Answers (1)

Avinash Raj
Avinash Raj

Reputation: 174874

You're almost there, just grab the datas which exists next to the access_token through capturing group.

Matcher m = Pattern.compile("(?i)\"access_token\":\s*\"([^\"]*)\"").matcher(s);
if(m.find()) {
    System.out.println(m.group(1));
}

DEMO

Upvotes: 3

Related Questions