在java中使用regex从字符串中提取数字 [英] Extract number from string using regex in java
问题描述
我无法使用正则表达式从预定义的输入String中提取(双重)数字。
字符串为:
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?
我迄今为止所尝试的:
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
注意这个表达式使小数部分(逗号后面)是可选的,但是n匹配输入,如 - ,01
。
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]+")
这篇关于在java中使用regex从字符串中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!