0

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)";
Tunaki
  • 132,869
  • 46
  • 340
  • 423
srinisunka
  • 1,159
  • 2
  • 7
  • 10

3 Answers3

3

You can use a positive lookbehind 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 `)`
System.out.println(newPath);

O/P :

(tags:homepage)(tags:project mindshare)(tags:5.5.x)(tags:project 5.x)
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
3

You can do this without using a regular expression, in a clean and simple way, that even supports nested parentheses (for the day you'll need to support them).

What you want to do here is to keep everything that is inside parentheses, so we can just loop over the characters and keep a count of open parentheses. If this count is greater than 0, we add the character (it means we're inside parens); if not, we disregard the character.

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

StringBuilder sb = new StringBuilder();
int openParens = 0;
for (char c : path.toCharArray()) {
    if (c == '(') openParens++;
    if (openParens > 0) sb.append(c);
    if (c == ')') openParens--;
}

System.out.println(sb.toString());

This has the advantage that you don't implicly rely on: having a single dot between parens, not having nested parens, etc.

Tunaki
  • 132,869
  • 46
  • 340
  • 423
0

Here is a simple approach.

System.out.println("(tags:homepage).(tags:project mindshare).(tags:5.5.x).(tags:project 5.x)".replaceAll("\\)\\.\\(", ")("));

output is

(tags:homepage)(tags:project mindshare)(tags:5.5.x)(tags:project 5.x)

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107