【问题标题】:Java searching float number in StringJava在String中搜索浮点数
【发布时间】:2012-09-02 09:53:08
【问题描述】:

假设我有这样的字符串:

eXamPLestring>1.67>>ReSTOfString

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

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

【问题讨论】:

标签: java regex floating-point


【解决方案1】:

如果您想从 String 中提取所有 Int'sFloat's,您可以关注我的解决方案:

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;
}

如果您还想解析 负值,可以将 [-]? 添加到模式中,如下所示:

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

如果您还想将 , 设置为分隔符,您可以将 ,? 添加到这样的模式中:

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

.

要测试模式,您可以使用此在线工具:http://gskinner.com/RegExr/

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

【讨论】:

    【解决方案2】:

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

    \\d+\\.\\d+
    

    这可能看起来像

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

    【讨论】:

      【解决方案3】:

      这是如何在一行中完成的,

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

      如果没有找到浮点数,则返回一个空白字符串。

      如果你真的想要float,你可以在一行中完成:

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

      但由于无法将空白解析为float,因此您必须分两步进行 - 在解析之前测试字符串是否为空白 - 如果可能没有浮点数。

      【讨论】:

      • 如果字符串中根本没有数字怎么办?它只是返回原始字符串而不是空字符串。
      • @FabZbi 我修改了正则表达式,如果没有浮点数则返回一个空白 - 我只是在捕获组之后添加了一个 ? 以使其成为可选。
      【解决方案4】:
          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());
          }
      

      只给出浮点数

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

      【讨论】:

        【解决方案5】:

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

        【讨论】:

          【解决方案6】:

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

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

          示例代码:

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

          输出:

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

          【讨论】:

            【解决方案7】:
            /**
             * 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);
                }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-12-24
              • 2011-02-25
              • 2011-01-08
              • 1970-01-01
              • 2021-03-18
              • 1970-01-01
              相关资源
              最近更新 更多