简体   繁体   English

使用正则表达式过滤并查找字符串中的整数

[英]Filter and find integers in a String with Regex

I have this long string: 我有这么长的字符串:

String responseData = "fker.phone.bash,0,0,0"
    + "fker.phone.bash,0,0,0"
    + "fker.phone.bash,2,0,0";

What I want to do is to extract the integers in this string. 我想做的是提取此字符串中的整数。 I have successfully done that with this code: 我已使用以下代码成功完成了此操作:

 String pattern = "(\\d+)";
 // this pattern finds EVERY integer. I only want the integers after       the comma

        Pattern pr = Pattern.compile(pattern);

        Matcher match = pr.matcher(responseData);


        while (match.find()) {

            System.out.println(match.group());

        }

So far it is working, but I want to make my regex more secure because the responsedata I get is dynamic. 到目前为止,它是可行的,但是我想使我的正则表达式更加安全,因为我得到的响应数据是动态的。 Sometimes I might get an integer in the middle of the string, but I only want the last integers, meaning after the comma. 有时我可能会在字符串的中间得到一个整数,但我只想要最后一个整数,即逗号之后。

I know the regex for starts with is ^ and I have to put my comma tecken as an argument, but I don't know how to piece it all together and that is why I am asking for help. 我知道以开头的正则表达式是^,我必须以逗号tecken作为参数,但是我不知道如何将它们拼凑起来,这就是为什么我寻求帮助。 Thank you. 谢谢。

String pattern = "(,)(\\d)+";

然后得到第二组。

You can use positive lookbehind for that: 您可以为此使用正向后看

String pattern = "(?<=,)\\d+";

You don't need to extract any groups to do use that solution, because lookbehind is zero-length assertion . 您不需要提取任何组即可使用该解决方案,因为向后看是零长度断言

You can simply use the following and find by match.group(1) : 您可以简单地使用以下内容并通过match.group(1)查找:

String pattern = ",(\\d+)";

See working demo 查看工作演示

You can also use word boundaries to get independent numbers: 您还可以使用单词边界来获取独立数字:

String pattern = "\\b(\\d+)\\b";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM