2013-09-25 106 views
0

假設我想逃避被嵌套雙引號內的所有雙引號(圖片CSV或東西):正則表達式查找和逃避雙引號用雙引號

"Jim", "Smythe", "Favorite Quote: "This is my favorite quote."" 

我想以隔離圍繞This is my favorite quote.的內部引號,然後用\轉義它們。但是我在編寫正則表達式以匹配內部引號時遇到了困難。因此,所產生的比賽,我想的是:

"Jim", "Smythe", "Favorite Quote: "This is my favorite quote."" 
            ^^      ^^ 
       Start Match Here ||      || End Match Here 
       Start Capture Here |  End Capture Here | 

Match: "This is my favorite quote." 
Capture: This is my favorite quote. 

然後,我可以很容易地逃避與圖案\"$1\"引號,以獲得最終結果:

"Jim", "Smythe", "Favorite Quote: \"This is my favorite quote.\"" 
+1

更換一般來說,你應該把它放在前行逃脫值。如果你事後做,你只能處理可以確定是報價而不是價值結束的情況。例如,如果引號是逗號,則無法將其與值分隔符區分開。 – Guffa

+0

我的第一個猜測是,這是不可能的,由於這個問題中指定的原因 - http://stackoverflow.com/questions/133601/can-regular-expressions-be-used-to-match-nested-patterns – dana

+0

Something像這樣:'/「(?:[^ \\」] | \\。)*「/'? – Brian

回答

1

我建議:

(?<!^|,)"(?=(?:(?<!"),|[^,])*"(?:,|$)) 

\\$0

regex101 demo

+0

您可以在前面使用帶@的符號,這樣就不必使用太多的轉義符,即'@「(?<!^ |,)」(?=(?:(?<! ),| [^,])*「(?:,| $))」'和'@「\\ $ 0」' – Jerry

+0

是的,謝謝,這是很好的 –

+0

@JoshM。不客氣:) – Jerry

1

這個工作對我來說:

string input = "\"Jim\" , \"Smythe\", \"Favorite Quote: \"This is my favorite quote.\"\""; 
var output = Regex.Match(input,"\"(?!\\s*,\\s*\")((?<!(,|^)\\s*\"\\w*?)[^\"]+)\"").Groups[1].Value; 
//output = This is my favorite quote. 

var replacedOutput = Regex.Replace(input, "\"(?!\\s*,\\s*\")((?<!(,|^)\\s*\"\\w*?)[^\"]+)\"", "\\\"$1\\\""); 
相關問題