Through regular expressions:
sub quadParse { my ($inputStr) = @_; my $str = "+".$inputStr; # as the first needn't have a sign $str =~ s/\s+//g; # normalise my $squared = $1 if ($str =~ m/([+-][0-9])*x\^2/); my $ex = $1 if ($str =~ m/([+-][0-9]*)x(?!\^)/); my $const = $1 if ($str =~ m/([+-][0-9]+)(?!x)/); return "${squared}, ${ex}, ${const}"; }
For parsing Perl strings.
Oh, move on:
public static String coeff(String str, String regex) { Pattern patt = Pattern.compile(regex); Matcher match = patt.matcher(str); // missing coefficient default String coeff = "+0"; if(match.find()) coeff = match.group(1); // always have sign, handle implicit 1 return (coeff.length() == 1) ? coeff + "1" : coeff; } public static String[] quadParse(String arg) { String str = ("+" + arg).replaceAll("\\s", ""); String quad = coeff(str, "([+-][0-9]*)x\\^2" ); String ex = coeff(str, "([+-][0-9]*)x(?!\\^)"); String cnst = coeff(str, "([+-][0-9]+)(?!x)" ); return new String[] {quad, ex, cnst}; }
Java test in ideone .
They process the formula in any order, with or without an initial character in the first term, and process the missing terms correctly. The Perl version does not commit "+" to "+1", etc. Or does not give an explicit "0" for missing terms, because I have run out of time.
Phil h
source share