Regex (Java): how to replace "||" with "| |" repeatedly

If I have a row of data separated by channels:

123456 | abcd ||| 65464 | hgfhgf

How to replace any event ||with | |:?

So, it will look like this:

123456 | abcd | | | 65464 | hgfhgf

I tried using a simple Java expression:

delimString.replaceAll("\\\|\\\|", "| |");

but this replaced only the first occurrence:

123456 | abcd | || 65464 | hgfhgf

So I need something to repeat (eagerly, I think).

+5
source share
4 answers
String resultString = subjectString.replaceAll("\\|(?=\\|)", "| ");

Regular explanation without double Java backslashes:

\|   # Match a literal |
(?=  # only if it followed by
 \|  # another literal |.
)    # End of lookahead assertion

You can even go into the wild and replace the empty space between two pipes with a space character:

String resultString = subjectString.replaceAll("(?<=\\|)(?=\\|)", " ");
+10
source

, 2- | , . while.

+1

I agree with Ingo - the loop solution is more lines of code, but more understandable (at least it does not need to be explained;)):

String test = "abc|def||ghi|||jkl";

StringBuilder result = new StringBuilder();
char previous = 0;
for (char c:test.toCharArray()) {
  if (c == '|' && previous == '|')
    result.append(" ");
  result.append(c);
  previous = c;
}

System.out.println(result);
+1
source

Sorry for my reply before I made a mistake. I just updated.

This is an alternative that will work 100%, be sure to look at it:

 public static void main(String [] args) {

        String data = "123456|abcd|||65464|hgfhgf";
        String modified = "";
        for(int i = 0; i < data.length();i++) {
            if(data.charAt(i) == '|') {
                modified += "| |";
            }
            else {
                modified += "" + data.charAt(i);
            }
        }
        System.out.print(modified);
}

In the end, it will look like this:

123456 | | ABCD | || || | 65464 | | Hgfhgf

0
source

All Articles