簡體   English   中英

C#無法轉義正則表達式字符串中的引號

[英]C# Cannot escape quotes in a regex string

我試圖使用正則表達式匹配引號,但我沒有設法在@string逃避它們 - 我收到一個錯誤:

output = Regex.Replace(str, @"[\d-']", string.Empty);    // valid

output = Regex.Replace(str, @"[\d-'\"]", string.Empty);  // not valid!

這個也行不通:

string str = "[\d-'\"]" // bad compile constant value!

要逃避"在逐字符串中,請使用""

Regex.Replace(str, @"[\d-'""]", string.Empty);

@ token抑制\\轉義。 如果刪除@標記它將按預期工作,但您必須轉義第一個反斜杠,即"[\\\\d-'\\"]"

我剛剛嘗試了這段代碼

output = Regex.Replace("Ciao'\"", @"[\d-'""]", string.Empty);
Console.Writeln(output);

這在控制台屏幕上產生了“Ciao”​​。 所以,正如DLeh所說,你應該使用""來逃避引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM