Reputation: 3189
I'm getting message from other program where some characters are changed:
\n
(enter) -> #
(hash) #
-> \#
\
-> \\\\
When I'm trying to reverse these change with my code it's not working, probably of that
Note that backslashes () and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.
This is my code:
public String changeChars(final String message) {
String changedMessage = message;
changedMessage = changePattern(changedMessage, "[^\\\\][#]", "\n");
changedMessage = changePattern(changedMessage, "([^\\\\][\\\\#])", "#");
changedMessage = changePattern(changedMessage, "[\\\\\\\\\\\\\\\\]", "\\\\");
return changedMessage;
}
private String changePattern(final String message, String patternString, String replaceString) {
Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher(message);
return matcher.replaceAll(replaceString);
}
Upvotes: 0
Views: 344
Reputation: 124265
I assume that your encoding method works like this.
\
with \\\\
#
as \#
#
have \
before it we can use it to mark new lines \n
with #
.Code for that could be something like
data = data.replace("\\", "\\\\\\\\");
data = data.replace("#", "\\#");
data = data.replace("\n", "#");
To reverse this operation we need to start from the end (form last replacement)
#
that don't have \
before it with new line \n
marks (if we started with 2nd replacement \#
-> #
we wouldn't know later which of #
ware replacements of \n
). \#
with #
(this way we will get rid of additional \
that wasn't in original String and it won't bother our last replacement step).\\\\
with \
.Here is how we can do it.
//your previous regex [^\\\\][#] describes "any character that is not \ and #
//but since we don't want to include that additional non `\` mark while replacing
//we should use negative look-behind mechanism "(?<!prefix)"
data = data.replaceAll("(?<!\\\\)#", "\n");
//now since we got rid of additional "#" its time to replace `\#` to `#`
data = data.replace("\\#", "#");
//and lastly `\\\\` to `\`
data = data.replace("\\\\\\\\", "\\");
Upvotes: 1