jymbo
jymbo

Reputation: 1375

Replace String between 2 strings in Java

I'm trying to find all occurrences of a set of strings and replace what is in between them within a new value. I have tried all of the examples for Java/ regex I have found on this site and none have worked. A sample of the string would look like this:

"TestValue 1 VARCHAR(10), TestValue2 FLOAT(126), TestValue3 FLOAT(135)"

I would want to find and replace all the values between "FLOAT(" and ")" with 53 so that the above string would be replaced with:

"TestValue 1 VARCHAR(10), TestValue2 FLOAT(53), TestValue3 FLOAT(53)"

How can I do this with a String.replaceAll ?

I have tried replaceAll("FLOAT(.*?)", "53") and it just replaces the FLOAT so the string looks like:

"TestValue 1 VARCHAR(10), TestValue2 53(126), TestValue3 53(135)"

Upvotes: 1

Views: 377

Answers (2)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

It's much simpler - your replacement is fixed (it doesn't depend on the matched text) - you always want to replace with FLOAT(53)

So use regex

FLOAT\(\d+\)

and replacement

FLOAT(53)

Upvotes: 2

Elliott Frisch
Elliott Frisch

Reputation: 201429

You can use \( and \) to escape the literal parenthesis, and then \d+ to match digits. Something like,

String s = "TestValue1 VARCHAR(10), TestValue2 FLOAT(126), TestValue3 FLOAT(135)";
System.out.println(s.replaceAll("FLOAT\\(\\d+\\)", "FLOAT(53)"));

Output is (as requested)

TestValue1 VARCHAR(10), TestValue2 FLOAT(53), TestValue3 FLOAT(53)

Upvotes: 3

Related Questions