extracting a number from a string in Java

ぃ、小莉子 提交于 2019-12-18 08:56:12

问题


I have a string with a number inside and I want to retrieve that number. for example if I have a string "bla bla 45 bla bla" I want to get the number 45. I have searched a bit and found out that this code should make the work

Matcher matcher = Pattern.compile("\\d+").matcher("bla bla 45 bla bla");
if(matcher.matches())
    String result = matcher.group();

but it doesn't :(
probably the problem is that "\d+" regular expression is converted to "^\d+$" and so the matcher doesn't matches the number inside the text.
Any ideas.


回答1:


You should use matcher.find() instead.




回答2:


Here's an example on how to use matcher.find()

    Matcher matcher = Pattern.compile("\\d+").matcher("bla bla 45 bla 22 bla");
    while(matcher.find()) {
        System.out.println(matcher.group());
    }

This will output

45
22


来源:https://stackoverflow.com/questions/1558432/extracting-a-number-from-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!