Java; String replace (using regular expressions)?

JavaRegex

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

str.replaceAll("\\^([0-9]+)", "<sup>$1</sup>");

Solution 2 - Java

private String removeScript(String content) {
	Pattern p = Pattern.compile("<script[^>]*>(.*?)</script>",
			Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
	return p.matcher(content).replaceAll("");
}

Solution 3 - Java

String input = "hello I'm a java dev" +
"no job experience needed" +
"senior software engineer" +
"java job available for senior software engineer";
		
String fixedInput = input.replaceAll("(java|job|senior)", "<b>$1</b>");

Solution 4 - Java

"5 * x^3 - 6 * x^1 + 1".replaceAll("\\W*\\*\\W*","").replaceAll("\\^(\\d+)","<sup>$1</sup>");

please note that joining both replacements in a single regex/replacement would be a bad choice because more general expressions such as x^3 - 6 * x would fail.

Solution 5 - Java

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
}

Solution 6 - Java

If this is for any general math expression and parenthetical expressions are allowed, it will be very difficult (perhaps impossible) to do this with regular expressions.

If the only replacements are the ones you showed, it's not that hard to do. First strip out *'s, then use capturing like Can Berk Güder showed to handle the ^'s.

Solution 7 - Java

What is your polynomial? If you're "processing" it, I'm envisioning some sort of tree of sub-expressions being generated at some point, and would think that it would be much simpler to use that to generate your string than to re-parse the raw expression with a regex.

Just throwing a different way of thinking out there. I'm not sure what else is going on in your app.

Solution 8 - Java

Try this:

String str = "5 * x^3 - 6 * x^1 + 1";
String replacedStr = str.replaceAll("\\^(\\d+)", "<sup>\$1</sup>");

Be sure to import java.util.regex.

Solution 9 - Java

class Replacement 
{
    public static void main(String args[])
    {
        String Main = "5 * x^3 - 6 * x^1 + 1";
        String replaced = Main.replaceAll("(?m)(:?\\d+) \\* x\\^(:?\\d+)", "$1x<sup>$2</sup>");
        System.out.println(replaced);
    }
}

Solution 10 - Java

You'll want to look into capturing in regex to handle wrapping the 3 in ^3.

Solution 11 - Java

Try this, may not be the best way. but it works

String str = "5 * x^3 - 6 * x^1 + 1";
str = str.replaceAll("(?x)(\\d+)(\\s+?\\*?\\s+?)(\\w+?)(\\^+?)(\\d+?)", "$1$3<sup>$5</sup>");
System.out.println(str);

Solution 12 - Java

Take a look at antlr4. It will get you much farther along in creating a tree structure than regular expressions alone.

https://github.com/antlr/grammars-v4/tree/master/calculator (calculator.g4 contains the grammar you need)

In a nutshell, you define the grammar to parse an expression, use antlr to generate java code, and add callbacks to handle evaluation when the tree is being built.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan BurzoView Question on Stackoverflow
Solution 1 - JavaCan Berk GüderView Answer on Stackoverflow
Solution 2 - JavaFlorianView Answer on Stackoverflow
Solution 3 - JavaHubbisonView Answer on Stackoverflow
Solution 4 - Javavit123View Answer on Stackoverflow
Solution 5 - JavaLieven KeersmaekersView Answer on Stackoverflow
Solution 6 - JavaMichael MyersView Answer on Stackoverflow
Solution 7 - JavaAdam JaskiewiczView Answer on Stackoverflow
Solution 8 - JavacdmckayView Answer on Stackoverflow
Solution 9 - JavaBigGinDaHouseView Answer on Stackoverflow
Solution 10 - JavaRyan GrahamView Answer on Stackoverflow
Solution 11 - Javauser5915163View Answer on Stackoverflow
Solution 12 - JavaGeoffrey RitcheyView Answer on Stackoverflow