如何使用正则表达式提取4位数字 [英] How to extract the 4 digit numbers using a regex

查看:2749
本文介绍了如何使用正则表达式提取4位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 company_id:部分之后提取所有数字并存储在变量中。我的字符串如下所示。

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\"}"

在这种情况下,正则表达式将提取数字 4100 3070 4061 。我的字符串上还有很多其他数字,我只是没有包含它们以节省空间。我想要的数字将是唯一的4位数字,并且总是在 company_id:部分之后。我尝试了以下

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.

推荐答案

您可以使用正则表达式 \company_id \检索所有公司ID:(\\\\ {4 })。这样可以确保只获得company_id元素后面的数字。它在一个组中捕获它。

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

您的String似乎无效JSON因此您无法使用JSON解析器。

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

在你的代码中,你只检索第一个id,因为你可能没有循环所有的匹配。

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

这篇关于如何使用正则表达式提取4位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆