开发者

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

开发者 https://www.devze.com 2023-02-22 07:59 出处:网络
If I have a string of pipe-delimited data: 123456|abcd|||65464|hgfhgf How can I replace any occurrance of || with: | |?

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| | |6546开发者_开发知识库4|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

0

精彩评论

暂无评论...
验证码 换一张
取 消