Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

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.

share|improve this question
    
What is it you're trying to do? Just give example input and output. All the info about your attempts is meaningless without context. –  Bohemian Jul 9 '13 at 23:29

1 Answer 1

up vote 1 down vote accepted

You can use groups for this:

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

$1 refers to the first thing in brackets.

Java regex reference.

share|improve this answer
    
Exactly what I needed, thanks. –  user1094607 Jul 9 '13 at 22:55
    
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 Jul 9 '13 at 22:55
    
@MadDogMcNamara $1 does work. –  user1094607 Jul 9 '13 at 22:57
1  
@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). –  Dukeling Jul 9 '13 at 23:02
    
Ah thank you. I was clearly confused. –  MadDogMcNamara Jul 9 '13 at 23:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.