从Java中的字符串中提取数字 [英] extracting a number from a string in Java

查看:101
本文介绍了从Java中的字符串中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有数字的字符串,我想要检索该数字。
例如,如果我有一个字符串bla bla 45 bla bla我想得到数字45.
我搜索了一下,发现这段代码应该可以完成工作

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();

但它没有:(左
可能问题是 \d +正则表达式转换为^ \d + $,因此匹配器与文本中的数字不匹配。

任何想法。

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.

推荐答案

您应该使用 matcher.find()代替。

这篇关于从Java中的字符串中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆