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
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
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]+")