我想在company_id: part之后提取所有数字并存储在变量中。 我的字符串看起来如下。
String company ="{\"company_id\":4100\"data\" \"drm_user_id\":572901936637129135\"company_id\":3070,\"data\",\"company_id\":4061,\"data\"}"在这种情况下,正则表达式将提取数字4100,3070和4061 。 我的字符串上还有很多其他数字,我只是没有包含它们以节省空间。 我想要的数字将是唯一的4位数字,并且总是在company_id: part之后。 我尝试了以下内容
Pattern pattern = Pattern.compile("(\\d{4})"); Matcher matcher = pattern.matcher(company);但是,这只返回第一个数字而不是其他两个数字。
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.
最满意答案
您可以使用regex \"company_id\":(\\d{4})检索所有公司ID \"company_id\":(\\d{4}) 。 这样可以确保只获取"company_id"元素后面的数字。 它在一个组中捕获它。
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解析器。
在你的代码中,你只检索第一个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); }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.
更多推荐
发布评论