简体   繁体   English

如何使用正则表达式转义和取消转义反斜杠和“”?

[英]How to escape and unescape backslashes and ''' with regex?

I need to escape all ''' and backslashes in a string .我需要转义string中的所有'''backslashes 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:示例 output:

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

I also need unescape backslashes and ''' .我还需要unescape backslashes'''

Example input:示例输入:

asdf \\\\ and \'''

Example output:示例 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.编辑:在尝试了评论 escaping 中建议的解决方案之后,但没有转义。

  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 Output

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

For escaping, you may use对于 escaping,您可以使用

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.在这里,您使用.replaceAll(r"\", r"\\")将所有反斜杠替换为双反斜杠,然后将所有'''子字符串替换为\'''子字符串。

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.在这里,您首先将所有\'''子字符串替换为'''子字符串,然后将双反斜杠替换为单个反斜杠。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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