Use Regex, the following template will work:
([+-]?\d+)[Xx]2\s*([+-]?\d+)[Xx]\s*([+-]?\d+)\s*=\s*0
This will match the quadratic and retrieve the parameters, allows you to decide how it works:
(...) this is a capture group[+-]?\d+ this corresponds to several digits preceded by the + or - option[Xx] this matches "x" or "x"\s* this matches zero or more spaces
So,
([+-]?\d+) matches the argument "a"[Xx]2 matches "X2" or "x2"\s* matches an optional space([+-]?\d+) matches the argument "b"[Xx] matches "X" or "x"\s* matches an optional space([+-]?\d+) matches the argument "c"\s*=\s*0 matches "= 0" with some optional spaces
Lets wrap this in a class :
private static final class QuadraticEq { private static final Pattern EQN = Pattern.compile("([+-]?\\d+)[Xx]2\\s*([+-]?\\d+)[Xx]\\s*([+-]?\\d+)\\s*=\\s*0"); private final int a; private final int b; private final int c; private QuadraticEq(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } public static QuadraticEq parseString(final String eq) { final Matcher matcher = EQN.matcher(eq); if (!matcher.matches()) { throw new IllegalArgumentException("Not a valid pattern " + eq); } final int a = Integer.parseInt(matcher.group(1)); final int b = Integer.parseInt(matcher.group(2)); final int c = Integer.parseInt(matcher.group(3)); return new QuadraticEq(a, b, c); } @Override public String toString() { final StringBuilder sb = new StringBuilder("QuadraticEq{"); sb.append("a=").append(a); sb.append(", b=").append(b); sb.append(", c=").append(c); sb.append('}'); return sb.toString(); } }
Pay attention to \\ , this is required by Java.
Quick test:
System.out.println(QuadraticEq.parseString("4x2-4x-42=0"));
Output:
QuadraticEq{a=4, b=-4, c=-42}
Boris the Spider
source share