简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM