Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

regex - extracting a number from a string in Java

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...