简体   繁体   中英

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)"

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM