Java; String replace (using regular expressions)?

Dan Burzo picture Dan Burzo · Mar 10, 2009 · Viewed 444.8k times · Source

As part of a project for school, I need to replace a string from the form:

5 * x^3 - 6 * x^1 + 1

to something like:

5x<sup>3</sup> - 6x<sup>1</sup> + 1

I believe this can be done with regular expressions, but I don't know how to do it yet.

Can you lend me a hand?

P.S. The actual assignment is to implement a Polynomial Processing Java application, and I'm using this to pass polynomial.toString() from the model to the view, and I want do display it using html tags in a pretty way.

Answer

Can Berk G&#252;der picture Can Berk Güder · Mar 10, 2009
str.replaceAll("\\^([0-9]+)", "<sup>$1</sup>");