简体   繁体   中英

Regex (Java): How do I replace “||” with “| |” repeatedly

If I have a string of pipe-delimited data:

123456|abcd|||65464|hgfhgf

How can I replace any occurrance of || with: | | | | ?

So it would end up looking like this:

123456|abcd| | |65464|hgfhgf

I tried using the simple Java expression:

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

but that only replaced the first occurrence:

123456|abcd| ||65464|hgfhgf

So I need something to make it repeat (greedily I think).

String resultString = subjectString.replaceAll("\\|(?=\\|)", "| ");

The regex explained without Java's double backslashes:

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

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

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

The problem is here that the match position is already past the 2nd | you replaced, so it does not count. You'll have to use a while loop to do this.

I agree with Ingo - a loop solution is more lines of code but easier to understand (at least it doesn't have 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);

Sorry about my answer before i made a mistake. I just updated.

This is an alternative that will work 100% sure have a 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);
}

At the end it will look like this:

123456| |abcd| || || |65464| |hgfhgf

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