Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java; String replace (using regular expressions)?

Tags:

java

regex

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.

like image 469
Dan Burzo Avatar asked Oct 15 '22 06:10

Dan Burzo


People also ask

Does string replace use regex?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.

What is replaceAll \\ s in Java?

Java String replaceAll() The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.

What do the replaceAll () do?

The replaceAll() method replaces each substring that matches the regex of the string with the specified text.


1 Answers

str.replaceAll("\\^([0-9]+)", "<sup>$1</sup>");
like image 192
Can Berk Güder Avatar answered Oct 18 '22 21:10

Can Berk Güder