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

编程入门 行业动态 更新时间:2024-10-28 16:25:13
如何使用正则表达式提取4位数字(How to extract the 4 digit numbers using a regex)

我想在company_id: part之后提取所有数字并存储在变量中。 我的字符串看起来如下。

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

在这种情况下,正则表达式将提取数字4100,30704061 。 我的字符串上还有很多其他数字,我只是没有包含它们以节省空间。 我想要的数字将是唯一的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.

更多推荐

本文发布于:2023-08-01 01:17:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1350487.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   数字   正则表达式   extract   numbers

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!