Java在String中搜索浮点数 [英] Java searching float number in String
问题描述
假设我有这样的字符串:
lockquote
eXamPLestring> 1.67 >> ReSTOfString
我的任务是从上面的字符串只提取1.67。
我认为正则表达式将是有用的,但我不能弄清楚如何编写propper表达式。如果你想提取所有的 Int
的s 从 字符串
和 浮动
的 >,你可以按照我的解决方案:
private ArrayList< String> parseIntsAndFloats(String raw){
ArrayList< String> listBuffer = new ArrayList< String>();
模式p = Pattern.compile([0-9] * \\\。?[0-9] +);
Matcher m = p.matcher(raw); (m.find()){
listBuffer.add(m.group());
while
}
return listBuffer;
如果您还想解析负值可以像这样添加 [ - ]?
:
Pattern p = Pattern.compile([ - ]?[0-9] * \\\。。?[0-9] +);
如果您还想设置 ,
作为分隔符,您可以将 ,
添加到此模式中:
Pattern p = Pattern.compile([ - ]?[0-9] * \\。?,?[0-9] +);
。
可以使用这个在线工具: http://gskinner.com/RegExr/
<注意:如果你正在尝试我的例子,那么记住要使用unescape(你只需要把
\
) let's say i have string like that:
eXamPLestring>1.67>>ReSTOfString
my task is to extract only 1.67 from string above.
I assume regex will be usefull, but i can't figure out how to write propper expression.
If you want to extract all Int
's and Float
's from a String
, you can follow my solution:
private ArrayList<String> parseIntsAndFloats(String raw) {
ArrayList<String> listBuffer = new ArrayList<String>();
Pattern p = Pattern.compile("[0-9]*\\.?[0-9]+");
Matcher m = p.matcher(raw);
while (m.find()) {
listBuffer.add(m.group());
}
return listBuffer;
}
If you want to parse also negative values you can add [-]?
to the pattern like this:
Pattern p = Pattern.compile("[-]?[0-9]*\\.?[0-9]+");
And if you also want to set ,
as a separator you can add ,?
to the pattern like this:
Pattern p = Pattern.compile("[-]?[0-9]*\\.?,?[0-9]+");
.
To test the patterns you can use this online tool: http://gskinner.com/RegExr/
Note: For this tool remember to unescape if you are trying my examples (you just need to take off one of the \
)
这篇关于Java在String中搜索浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!