java Java在字符串中搜索浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12234963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 08:07:38  来源:igfitidea点击:

Java searching float number in String

javaregexfloating-point

提问by Damian Drewulski

let's say i have string like that:

假设我有这样的字符串:

eXamPLestring>1.67>>ReSTOfString

示例字符串>1.67>>ReSTOfString

my task is to extract only 1.67 from string above.

我的任务是从上面的字符串中仅提取 1.67。

I assume regex will be usefull, but i can't figure out how to write propper expression.

我认为正则表达式会很有用,但我不知道如何编写正确的表达式。

回答by Ryan Amaral

If you want to extract all Int'sand Float'sfrom a String, you can follow my solution:

如果要从 a 中提取所有Int'sFloat'sString,可以按照我的解决方案进行操作:

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 valuesyou can add [-]?to the pattern like this:

如果您还想解析负值,您可以[-]?像这样添加到模式中:

    Pattern p = Pattern.compile("[-]?[0-9]*\.?[0-9]+");

And if you also want to set ,as a separatoryou 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/

要测试模式,您可以使用此在线工具: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 \)

注意:对于此工具,如果您正在尝试我的示例,请记住取消转义(您只需要取消其中一个\

回答by Johan Sj?berg

You could try matching the digits using a regular expression

您可以尝试使用正则表达式匹配数字

\d+\.\d+

This could look something like

这可能看起来像

Pattern p = Pattern.compile("\d+\.\d+");
Matcher m = p.matcher("eXamPLestring>1.67>>ReSTOfString");
while (m.find()) {
    Float.parseFloat(m.group());
}

回答by Nishant

    String s = "eXamPLestring>1.67>>ReSTOfString>>0.99>>ahgf>>.9>>>123>>>2323.12";
    Pattern p = Pattern.compile("\d*\.\d+");
    Matcher m = p.matcher(s);
    while(m.find()){
        System.out.println(">> "+ m.group());
    }

Gives only floats

只提供浮点数

>> 1.67
>> 0.99
>> .9
>> 2323.12

回答by Bohemian

Here's how to do it in one line,

这是在一行中完成的方法,

String f = input.replaceAll(".*?([\d.]+).*", "");

If you actually want a float, here's how you do it in one line:

如果你真的想要一个float,这里是你如何在一行中做到的:

float f = Float.parseFloat(input.replaceAll(".*?([\d.]+).*", "")),

回答by lpinto.eu

/**
 * Extracts the first number out of a text.
 * Works for 1.000,1 and also for 1,000.1 returning 1000.1 (1000 plus 1 decimal).
 * When only a , or a . is used it is assumed as the float separator.
 *
 * @param sample The sample text.
 *
 * @return A float representation of the number.
 */
static public Float extractFloat(String sample) {
    Pattern pattern = Pattern.compile("[\d.,]+");
    Matcher matcher = pattern.matcher(sample);
    if (!matcher.find()) {
        return null;
    }

    String floatStr = matcher.group();

    if (floatStr.matches("\d+,+\d+")) {
        floatStr = floatStr.replaceAll(",+", ".");

    } else if (floatStr.matches("\d+\.+\d+")) {
        floatStr = floatStr.replaceAll("\.\.+", ".");

    } else if (floatStr.matches("(\d+\.+)+\d+(,+\d+)?")) {
        floatStr = floatStr.replaceAll("\.+", "").replaceAll(",+", ".");

    } else if (floatStr.matches("(\d+,+)+\d+(.+\d+)?")) {
        floatStr = floatStr.replaceAll(",", "").replaceAll("\.\.+", ".");
    }

    try {
        return new Float(floatStr);
    } catch (NumberFormatException ex) {
        throw new AssertionError("Unexpected non float text: " + floatStr);
    }
}

回答by Jesper Fyhr Knudsen

You can use the regex \d*\.?,?\d*This will work for floats like 1.0 and 1,0

您可以使用正则表达式\d*\.?,?\d*这将适用于 1.0 和 1,0 之类的浮点数

回答by LumenAlbum

Have a look at this link, they also explain a few things that you need to keep in mind when building such a regex.

看看这个链接,他们还解释了构建这样一个正则表达式时需要记住的一些事情。

[-+]?[0-9]*\.?[0-9]+

[-+]?[0-9]*\.?[0-9]+

example code:

示例代码:

String[] strings = new String[3];

    strings[0] = "eXamPLestring>1.67>>ReSTOfString";
    strings[1] = "eXamPLestring>0.57>>ReSTOfString";
    strings[2] = "eXamPLestring>2547.758>>ReSTOfString";

    Pattern pattern = Pattern.compile("[-+]?[0-9]*\.?[0-9]+");

    for (String string : strings)
    {
        Matcher matcher = pattern.matcher(string);
        while(matcher.find()){
            System.out.println("# float value: " + matcher.group());
        }
    }

output:

输出:

# float value: 1.67
# float value: 0.57
# float value: 2547.758