Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String.replaceAll with different match & replace criteria

Tags:

java

string

regex

I have this code:

String polynomial = "2x^2-4x+16";
String input = polynomial.replaceAll("[0-9a-zA-Z][-]", "+-");

The problem is I don't want to actually replace the [0-9a-zA-Z] char.

Previously, I had used polynomial.replace("-","+-"); but that gave incorrect output with negative powers.

The new criteria [0-9a-zA-Z][-] solves the negative power issue; however it replaces a char when I only need to insert the + before the - without deleting that char.

How can I replace this pattern using the char removed like:

polynomial.replaceAll("[0-9a-zA-Z][-]", c+"+-");

where 'c' represents that [0-9a-zA-Z] char.

like image 947
user1094607 Avatar asked Jan 22 '26 13:01

user1094607


1 Answers

You can use groups for this:

polynomial.replaceAll("([0-9a-zA-Z])[-]", "$1+-");

$1 refers to the first thing in brackets.

Java regex reference.

like image 120
Bernhard Barker Avatar answered Jan 24 '26 03:01

Bernhard Barker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!