繁体   English   中英

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

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

我需要转义string中的所有'''backslashes 因此,如果用户输入\ ,它应该被转换为\\或者如果用户输入''' ,它应该被转换为\'''

示例输入:

This is a test \. ABCDE ''' DEFG

示例 output:

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

我还需要unescape backslashes'''

示例输入:

asdf \\\\ and \'''

示例 output:

asdf \\ and '''            

我试过这样的东西,但它不工作....

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

编辑:在尝试了评论 escaping 中建议的解决方案之后,但没有转义。

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

测试

  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

对于 escaping,您可以使用

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

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

为了避免转义,您可以使用

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

在这里,您首先将所有\'''子字符串替换为'''子字符串,然后将双反斜杠替换为单个反斜杠。

暂无
暂无

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

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