0

I am converting a string by replacing all spaces to "_" and if there is "_" in actual string , I am converting it to "\_". If have a string like "this is test _string" result will be "this_is_test_\_string", now I want to use java regex to get back original string "this is test _string". Is it possible to achieve using java regex ?. Please help me out.

1

1 Answer 1

7

No, it is not possible to get back the original string because you did not escape backslash which makes it ambiguous whether "\\_" came from "_" or "\\ ".

If you had done

  1. Replace all occurrences of "\\" with "\\\\"
  2. Replace all occurrences of "_" with "\\_"
  3. Replace all occurrences of " " with "_"

then you can reverse the process by looking for the tokens "\\\\", "\\_", "_" in a single left to right pass.

In Java, the first transform is

stringToEncode.replace("\\", "\\\\").replace("_", "\\_").replace(" ", "_")

and the dual is

String decode(String stringToDecode) {
  int n = stringToDecode.length();
  StringBuilder out = new StringBuilder(n);
  int decoded = 0;
  for (int i = 0; i < n; ++i) {
    switch (stringToDecode.charAt(i)) {
      case '\\':
        out.append(stringToDecode, decoded, i);
        decoded = ++i;
        break;
      case '_':
        out.append(stringToDecode, decoded, i).append(' ');
        decoded = i+1;
        break;
    }
  }
  return decoded != 0
      ? out.append(stringToDecode, decoded, n).toString()
      : stringToDecode;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I tried for the string "this is _test" , encoded string I got is "this_is_\_test" which is excepted. But decoded string is "this is \ test" . Which results in wrong string.
@Senthilnathan, Yeah. The decoding is not a simple swap and reverse of the input because there is overlap. Will edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.