3

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.

1
  • What is it you're trying to do? Just give example input and output. All the info about your attempts is meaningless without context. Commented Jul 9, 2013 at 23:29

1 Answer 1

4

You can use groups for this:

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

$1 refers to the first thing in brackets.

Java regex reference.

Sign up to request clarification or add additional context in comments.

2 Comments

docs.oracle.com/javase/tutorial/essential/regex/groups.html : There it says that backreferences are made by \1, \2 ... \n, not $1. I don't know that $1, ... won't work, but thought I'd mention it
@MadDogMcNamara \1 is for group references from inside the regular expression while $1 is for group references in replace... (following a few links from String.replaceAll gets you here).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.