Java在String中搜索浮点数 [英] Java searching float number in String

查看:175
本文介绍了Java在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屋!

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