import java.util.regex.PatternSyntaxException;
// (:?\d+) \* x\^(:?\d+)
//
// Options: ^ and $ match at line breaks
//
// Match the regular expression below and capture its match into backreference number 1 «(:?\d+)»
// Match the character “:” literally «:?»
// Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
// Match a single digit 0..9 «\d+»
// Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
// Match the character “ ” literally « »
// Match the character “*” literally «\*»
// Match the characters “ x” literally « x»
// Match the character “^” literally «\^»
// Match the regular expression below and capture its match into backreference number 2 «(:?\d+)»
// Match the character “:” literally «:?»
// Between zero and one times, as many times as possible, giving back as needed (greedy) «?»
// Match a single digit 0..9 «\d+»
// Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
try {
String resultString = subjectString.replaceAll("(?m)(:?\\d+) \\* x\\^(:?\\d+)", "$1x<sup>$2</sup>");
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
} catch (IllegalArgumentException ex) {
// Syntax error in the replacement text (unescaped $ signs?)
} catch (IndexOutOfBoundsException ex) {
// Non-existent backreference used the replacement text
}