danilo
danilo

Reputation: 844

How to extract the 4 digit numbers using a regex

I want to extract all the numbers after the company_id: part and store in a variable. My string looks the following.

String company ="{\"company_id\":4100\"data\" \"drm_user_id\":572901936637129135\"company_id\":3070,\"data\",\"company_id\":4061,\"data\"}"

In this case, the regex would extract numbers 4100, 3070 and 4061. I have many other numbers on my string, I just did not include them to save space. The numbers I want will be the only ones with 4 digits and will always come after the company_id: part. I tried the following

Pattern pattern = Pattern.compile("(\\d{4})");
Matcher matcher = pattern.matcher(company);

However, that only returns the first digit and not the other two.

Upvotes: 3

Views: 2150

Answers (2)

Tunaki
Tunaki

Reputation: 137064

You can retrieve all the company ids using the regex \"company_id\":(\\d{4}). This makes sure that you only get the numbers after the "company_id" element. It captures it in a group.

String company ="{\"company_id\":4100\"data\" \"drm_user_id\":572901936637129135\"company_id\":3070,\"data\",\"company_id\":4061,\"data\"}";
Pattern pattern = Pattern.compile("\"company_id\":(\\d{4})");
Matcher matcher = pattern.matcher(company);
while (matcher.find()) {
    String companyId = matcher.group(1);
    System.out.println(companyId);
}

It seems that your String is not valid JSON so you can't use a JSON parser.

In your code, you only retrieve the first id because you problably didn't loop on all the matches.

Upvotes: 5

Chintan Ghate
Chintan Ghate

Reputation: 189

If the 4-digit number are always going to appear right after "company_id", then you could use this "company_id:[0-9]{4}" regex pattern to match all instances.

Upvotes: 0

Related Questions