我需要将'''
中的所有backslashes
和string
逸出。因此,如果用户输入\
,则应将其转换为\\
;如果用户输入'''
,则应将其转换为\'''
。
输入示例:
This is a test \. ABCDE ''' DEFG
示例输出:
This is a test \\. ABCDE \''' DEFG
我还需要 unescape
backslashes
和'''
。示例输入:
asdf \\\\ and \'''
示例输出:
asdf \\ and '''
我尝试了类似的方法,但是它不起作用。
input = input.replaceAll(new RegExp(r'\\'), '\\\\')
编辑:
从注释中尝试建议的解决方案后,转义有效,但无法转义。
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);
});
输出
Expected: ' \\ TESTTEST '
Actual: ' \\\\\\\\ TESTTEST '
Which: is different.
Expected: \\ TESTTEST ...
Actual: \\\\\\\\ TES ...
^
Differ at offset 3
最佳答案
为了逃避,您可以使用
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
在这里,您首先将所有
\'''
子字符串替换为'''
子字符串,然后将两个反斜杠替换为单个反斜杠。
关于regex - 如何使用正则表达式对反斜杠和 ''进行转义和不转义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61346649/