srinisunka srinisunka - 1 year ago 82
Java Question

Java split and replace

I have the following string

String path = "(tags:homepage).(tags:project mindshare).(tags:5.5.x).(tags:project 5.x)";

I used following code,

String delims = "\\.";

String[] tokens = path.split(delims);
int tokenCount = tokens.length;
for (int j = 0; j < tokenCount; j++) {
System.out.println("Split Output: "+ tokens[j]);

Current output is

Split Output: (tags:homepage)
Split Output: (tags:project mindshare)
Split Output: (tags:5
Split Output: 5
Split Output: x)
Split Output: (tags:project 5
Split Output: x)

End goal is to convert this string into

String newpath = "(tags:homepage)(tags:project mindshare)(tags:5.5.x)(tags:project 5.x)";

Answer Source

You can use a positive-look behind to achieve this :

String path = "(tags:homepage).(tags:project mindshare).(tags:5.5.x).(tags:project 5.x)";
String newPath = path.replaceAll("(?<=\\))\\.", ""); // look for periods preceeded by `)`

O/P :

(tags:homepage)(tags:project mindshare)(tags:5.5.x)(tags:project 5.x)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download