Extracting a number from a string in Java

I have a string with a number inside and I want to get that number. for example, if I have the line "bla bla 45 bla bla", I want to get the number 45. I searched a bit and found out that this code should do the job

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

but this is not so :(
probably the problem is that the regular expression "\ d +" is converted to "^ \ d + $", and therefore the match does not match the number inside the text.
Any ideas.

+3
source share
2 answers

Instead, use matcher.find() .

+5
source

Here is an example using matcher.find ()

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

This will lead to the conclusion

 45 22 
+11
source

Source: https://habr.com/ru/post/916544/


All Articles