java 在java中使用正则表达式从字符串中提取数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15894729/
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 21:12:43  来源:igfitidea点击:

Extract number from string using regex in java

javaregexfunctiondebuggingparsing

提问by user2260250

I fail to extract a (double) number from a pre-defined input String using a regular expression.
The String is:

我无法使用正则表达式从预定义的输入字符串中提取(双)数字。
字符串是:

String inputline ="Neuer Kontostand";"+2.117,68";

For successfully parsing just the number I need to suppress the leading +while keeping an optional -. In addition I must cut off the "before/after the number.

为了成功解析我需要抑制前导的数字,+同时保持可选的-. 此外,我必须切断"数字之前/之后。

Of course I could do multi-step string-operations, but does anyone know how to do all in a more elegant way using one regular expression?

当然,我可以进行多步字符串操作,但是有谁知道如何使用一个正则表达式以更优雅的方式完成所有操作?

What I tried so far:

到目前为止我尝试过的:

Pattern p = Pattern.compile("-{0,1}[0-9.,]*");
Matcher m = p.matcher(inputline);
String substring =m.group();

回答by Tomalak

Pattern.compile("-?[0-9]+(?:,[0-9]+)?")

Explanation

解释

-?        # an optional minus sign
[0-9]+    # decimal digits, at least one
(?:       # begin non-capturing group
  ,       #   the decimal point (German format)
  [0-9]+  #   decimal digits, at least one
)         # end non-capturing group, make optional

Note that this expression makes the decimal part (after the comma) optional, but does not match inputs like -,01.

请注意,此表达式使小数部分(逗号后)成为可选的,但与-,01.

If your expected input alwayshas both parts (before and after the comma) you can use a simpler expression.

如果您的预期输入始终包含两个部分(逗号前后),您可以使用更简单的表达式。

Pattern.compile("-?[0-9]+,[0-9]+")

回答by Aubin

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NumRegEx {

   public static void main( String[] args ) {
      String inputline = "\"Neuer Kontostand\";\"+2.117,68\"";
      Pattern p = Pattern.compile(".*;\"(\+|-)?([0-9.,]+).*");
      Matcher m = p.matcher( inputline );
      if( m.matches()) { // required
         String sign  = m.group( 1 );
         String value = m.group( 2 );
         System.out.println( sign );
         System.out.println( value );
      }

   }
}

Output:

输出:

+
2.117,68