簡體   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