Extract number from string using regex in java

前端 未结 2 1923
星月不相逢
星月不相逢 2021-01-29 05:36

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.11         


        
2条回答
  •  野的像风
    2021-01-29 05:56

    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.

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

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

提交回复
热议问题