簡體   English   中英

在Java中使用正則表達式從字符串中提取數字

[英]Extract number from string using regex in java

我無法使用正則表達式從預定義的輸入String中提取(雙)數字。
字符串是:

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

為了僅成功解析數字,我需要在保留可選-同時抑制前導+ 另外,我必須刪掉數字前后的"

當然,我可以執行多步字符串操作,但是有人知道如何使用一個正則表達式以更優雅的方式完成所有操作嗎?

到目前為止我嘗試過的是:

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

說明

-?        # 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

請注意,此表達式使小數部分(逗號后)成為可選,但與-,01類的輸入不匹配。

如果您期望的輸入始終包含兩個部分(逗號前后),則可以使用更簡單的表達式。

Pattern.compile("-?[0-9]+,[0-9]+")
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 );
      }

   }
}

輸出:

+
2.117,68

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM