in commons-numbers-complex/src/main/java/org/apache/commons/numbers/complex/Complex.java [366:423]
public static Complex parse(String s) {
final int len = s.length();
if (len < FORMAT_MIN_LEN) {
throw new NumberFormatException(
parsingExceptionMsg("Input too short, expected format",
FORMAT_START + "x" + FORMAT_SEP + "y" + FORMAT_END, s));
}
// Confirm start: '('
if (s.charAt(0) != FORMAT_START) {
throw new NumberFormatException(
parsingExceptionMsg("Expected start delimiter", FORMAT_START, s));
}
// Confirm end: ')'
if (s.charAt(len - 1) != FORMAT_END) {
throw new NumberFormatException(
parsingExceptionMsg("Expected end delimiter", FORMAT_END, s));
}
// Confirm separator ',' is between at least 2 characters from
// either end: "(x,x)"
// Count back from the end ignoring the last 2 characters.
final int sep = s.lastIndexOf(FORMAT_SEP, len - 3);
if (sep < BEFORE_SEP) {
throw new NumberFormatException(
parsingExceptionMsg("Expected separator between two numbers", FORMAT_SEP, s));
}
// Should be no more separators
if (s.indexOf(FORMAT_SEP, sep + 1) != -1) {
throw new NumberFormatException(
parsingExceptionMsg("Incorrect number of parts, expected only 2 using separator",
FORMAT_SEP, s));
}
// Try to parse the parts
final String rePart = s.substring(1, sep);
final double re;
try {
re = Double.parseDouble(rePart);
} catch (final NumberFormatException ex) {
throw new NumberFormatException(
parsingExceptionMsg("Could not parse real part", rePart, s));
}
final String imPart = s.substring(sep + 1, len - 1);
final double im;
try {
im = Double.parseDouble(imPart);
} catch (final NumberFormatException ex) {
throw new NumberFormatException(
parsingExceptionMsg("Could not parse imaginary part", imPart, s));
}
return ofCartesian(re, im);
}