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).
Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.
The replaceFirst() and replaceAll() methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences.
Backslashes in Java. The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With