Frederik
Frederik

Reputation: 1303

How to escape and unescape backslashes and ''' with regex?

I need to escape all ''' and backslashes in a string. So if the user inputs \, it should get transformed to \\ or if the user inputs ''', it should get transformed to \'''.

Example input:

This is a test \. ABCDE ''' DEFG

Example output:

This is a test \\. ABCDE \''' DEFG

I also need unescape backslashes and '''.

Example input:

asdf \\\\ and \'''

Example output:

asdf \\ and '''            

I tried something like this, but it's not working....

 input = input.replaceAll(new RegExp(r'\\'), '\\\\')

Edit: After trying the suggested solution from the comments escaping works, but unescaping not.

  String unescape(String input) {
    return input.replaceAll(r"\'''", r"'''").replaceAll(r"\\", r"\");
  }

Test

  test("Unescape", () {
      String test = r" \\ TESTTEST ";
      String expected = r" \ TESTTEST ";
      expect(stringUtils.unescape(test), expected);
    });

Output

Expected: ' \\ TESTTEST '
Actual: ' \\\\\\\\ TESTTEST '
Which: is different.
            Expected:  \\ TESTTEST  ...
              Actual:  \\\\\\\\ TES ...
                         ^
             Differ at offset 3

Upvotes: 1

Views: 1864

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627607

For escaping, you may use

print(r"This is a test \. ABCDE ''' DEFG".replaceAll(r"\", r"\\").replaceAll(r"'''", r"\'''"));
// => This is a test \\. ABCDE \''' DEFG

Here, you replace all backslashes with double backslashes with .replaceAll(r"\", r"\\") and then replace all ''' substrings with \''' substrings.

For unescaping, you may use

print(r"This is a test \\. ABCDE \''' DEFG".replaceAll(r"\'''", r"'''").replaceAll(r"\\", r"\"));
// => This is a test \. ABCDE ''' DEFG

Here, you replace all \''' substrings with ''' substrings first, then replace double backslashes with single ones.

Upvotes: 1

Related Questions